text stringlengths 37 1.41M |
|---|
def Add(num1,num2):
while(num2!=0):
carry = num1 & num2
num1 = num1^num2
num2 = carry<<1
return num1
def recursive_Add(x,y):
if (y==0):
return x
else:
return recursive_Add(x^y,(x&y) << 1)
print(recursive_Add(32,61))
|
def fibonacci(n):
if n<0:
print("Incorrect input")
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fibonocci(n-1)+fibonocci(n-2)
#print(fibonacci(5))
def fibonacci(n):
f = [0,1]
for i in range(2,n):
f.append(f[i-1]+f[i-2])
return f[n]
#print(... |
def simple_reverse(string):
new_string = []
for i in range(len(string)-1,-1,-1):
new_string.append(string[i])
return ''.join(new_string)
string = "Hello"
#print(simple_reverse(string))
def swap(string,a,b):
string = list(string)
temp = string[a]
string[a] = string[b]
string[b] = te... |
import math
# =============================================================================================================== #
# THIS CLASS IS IN CHARGE OF DISPLAYING A MESSAGE FRAME, SIMILAR TO A MENU, BUT WITH NO OPTIONS
class GameMessageFrame:
def __init__(self, lines, padt=0, padb=0):
self.lines = lin... |
import random
# THIS FILE IS IN CHARGE OF ANYTHING TO DO WITH ROLLING THE RANDOM DICE USED IN THE GAME
# ============================================================================================================= #
# ROLLS A RANDOM DICE, FORMAT IS 'XdY', WHERE x IS THE AMOUNT OF DIE TO ROLL, AND Y IS THE TYPE OF DI... |
class DoublyCircNode(object):
def __init__ (self, d, n = None, p = None):
self.data = d
self.next = n
self.prev = p
def get_data(self):
return self.data
def set_next(self, new_next):
self.next = new_next
def set_prev(self, new_prev):
self.prev = new_prev
... |
a, b, c, = 3, 4, 5
print(a + b * c)
print((a + b) * c)
print("3^4 =", a ** b)
print(a / b)
print(a // b)
print(a % b)
print(b / 2)
print(b // 2)
print(b % 2)
|
"""
David R. Winer
drwiner@cs.utah.edu
Machine Learning HW1 Implementation
"""
from collections import namedtuple
import unicodedata
import math
Label = namedtuple('Label', ['label', 'firstname', 'middlename', 'lastname', 'lastname_length'])
def strip_accents(s):
return ''.join(c for c in unicodedata.normalize('NF... |
from array import array
numbers = array("h", [-2, -1, 0, 1, 2])
memv = memoryview(numbers)
print(len(memv))
print(memv[0])
memv_oct = memv.cast("B")
print(memv_oct.tolist())
print(numbers)
memv_oct[5] = 4
print(numbers)
def calculate_element(sequence):
res = {}
for e in set(sequence):
res[e] = seque... |
import argparse
"""
[root@ykyk argument_parse]# python ArgumentParse.py
Namespace(boolean_switch=False, server='localhost')
('host = ', 'localhost')
('boolean_switch = ', False)
[root@ykyk argument_parse]# python ArgumentParse.py --host 127.0.0.1 -t
Namespace(boolean_switch=True, server='127.0.0.1')
('host = ', '127.... |
'''
Python有许多内置的api,允许调用者传入参数, 以定制其行为
api在执行的时候,会通过这些钩子函数,回调函数的代码
比如list类型的sort方法接受可选的key参数,用以指定每个索引位置上的值
之间应该如果排序
'''
names = ["scorates", "archimedes", "plato", "aritotle"]
names.sort(key=lambda x: len(x))
print(names)
'''
其他编程语言可能会用抽象类来定义挂钩,然而在Python中,很多钩子函数只是
无状态的函数,这些函数有明确的参数及返回值,用函数做挂钩... |
"""
This program has a turtle that will ask you whether you would like to see a drawing or a fractal
"""
import turtle
def draw_square(turtle):
for i in range(4):
turtle.forward(50)
turtle.right(90)
def draw_triangle(turtle):
turtle.right(45)
turtle.forward(100)
turtle.right(90)
... |
from ascii_art import logo
import random
EASY_LEVEL_TURNS = 12
HARD_LEVEL_TURNS = 6
def check_answer(guess, answer):
if guess > answer:
print("Too high")
elif guess < answer:
print("Too low")
else:
print(f"You got it. The answer was {answer}")
def set_difficulty():
level = i... |
# Uses python3
import sys
def binary_search(b, y):
low, high = 0, len(b) - 1
while low <= high:
mid = int(low + (high - low) / 2)
if y == b[mid]:
return mid
elif y < b[mid]:
high = mid - 1
else:
low = mid + 1
return -1
if __name__ == '_... |
# Uses python3
import sys
def pisano(m):
previous = 0
current = 1
i = 0
while True:
previous, current = current, (previous + current) % m
i += 1
if previous == 0:
if current == 1:
return i
def fib_mod(n, m):
n = n % pisano(m)
previous = 0
... |
class DynamicArray:
def __init__(self, capacity=0):
self.count = 0
self.capacity = capacity
self.storage = [None] * self.capacity
def insert(self, index, value):
if index >= self.count:
return ("Index out of bound!")
|
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
''' use 2 pointer to find the answer in O(n^2) '''
res = []
nums.sort()
lenth = len(nums)
# if lenth < 3, it's impossible to find the answer
if lenth<3:
return []
... |
VALUE = 0
NEXT = 1
PREV = 2
def add_to_back_2(value, head, tail): #1
item = [value, None]
if head is None:
head = item
else:
tail[NEXT] = item
tail = item
return head, tail
def add_to_the_front(value, head, tail): #2
item = [value, None]
if head is None... |
"""
--------------------------------------------------------
1. Conditionals
--------------------------------------------------------
a. if: elif: else:
b. while condition:
c. break:
d. continue:
e. exit()
f. for i in range(stop) // default start = 0, step = 1
for i in range(start,stop)
for i in range(start,stop,step)... |
#################################################################
# Diagrama de Gantt Básico para Programación de la Producción #
# Autor: Rodrigo Maranzana #
# Contacto: https://www.linkedin.com/in/rodrigo-maranzana #
# Fecha: Octubre 2020 ... |
class Card(object):
def __init__(self, color, number = 0):
self._color = color
self._number = number
def __repr__(self):
return (self._color, self._number)
def __str__(self):
return self._color + ":" + str(self._number)
def __cmp__(self, other):
'''Compari... |
import logging
logging.basicConfig(format='%(asctime)s %(message)s',filename='4.log',level=logging.DEBUG)
try:
n=int(raw_input("Enter a number:"))
logging.info("Number accepted from user")
n=str(n)
sum=0
for i in n:
sum=sum+int(i)
logging.info("sum of digits is calculated")
print "The sum of digits is: " + st... |
def countNegatives(grid):
List = list()
ans = 0
for i in grid:
List += i
for i in List:
if i < 0:
ans += 1
else:
ans += 0
return ans
grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
print(countNegatives(grid)) |
# List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
distance = [1,2,3,4]
start = 0
destination =... |
paragraph = ["i", "love", "leetcode", "i", "love", "coding"]
def wordcounter(paragraph):
ans = []
tracker = {}
for word in paragraph:
if word not in tracker:
tracker[word] = 1
else:
tracker[word] = int(tracker.get(word)) + 1
for keyValue in tracker:
... |
def PhoneLetterConbination(input):
mapping = {
'1' : 'abc',
'2' : 'def',
'3' : 'ghi',
'4' : 'jkl',
'5' : 'mno',
'6' : 'pqr',
'7' : 'stu',
'8' : 'wxyz',
'9' : '',
... |
nums = [2,7,11,15]
target = 9
seen = dict()
for (index,key) in (enumerate(nums)):
##print(index,key)
remaining = target - nums[index]
if remaining not in seen:
seen[key] = index
else:
print("1")
print(seen[remaining],index) |
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" : break # if "done" is introduced the program end.
try:
var1 = int(num)
except:
print("Invalid input")
continue
if smallest is None:
smallest = var1
... |
#python program to find the largest
print('python program to find the largest: ')
a=float(input("enter first number: "))
b=float(input("enter second number: "))
c=float(input("enter third number: "))
if (a>b) and (a>c):
largest=a
elif (b>a) and (b>c):
largest=b
else:
largest=c
print("The largest number is ... |
#Temperature convertor
def displayMenu():
print 'Temperature converter menu';
print '(1) Convert Fahrenheit to Celsius';
print '(2) Convert Celsius to Fahrenheit';
print '(3) Convert Celsius to Kelvin';
print '(4) Convert Kelvin to Celsius';
print '(5) Convert Fahrenheit to Kelvin';
print '(... |
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)
def mul(x,y):
return (x*y)
def div(x,y):
if (y==0):
print("Undefined")
else:
return (x/y)
print add(5,3)
print sub(5,3)
print mul(5,3)
print div(5,0)
print div(6,3)
|
class Person:
def __init__(self, name, surname, date_of_birth, address):
self.name = name
self.surname = surname
self.date_of_birth = date_of_birth
self.address = address
def __str__(self):
return self.name + " " + self.surname
class Employee(Person):
num_of_emp... |
#Iterative statements
#if we want to execute a group of statements multiple times then we should go for iterative statements
# for loop if we want to execute some action for every element in the sequence(it may be string or collection) then we should go for iterative for loop
s="no one love solder untill enemy is at t... |
#Exercise 9 -- Printing, Printing, Printing PTHW
#Here's some new strange stuff, remember type it exactly
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
#Affichage basique
print("Here are the days: ", days)
print("Here are the months: ", months)
#Affichage sur plusieurs ligne... |
#Exercise 16 -- Reading and Writting Files
#Importation de argv
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
#Attente pour poursuivre ou pas
input('?')
#ouverture du fichier
target ... |
list_from_user_str = input("Введите нескольких слов, разделённых пробелами: ").split()
count = 1 # без range() для разнообразия, зато тернарный оператор!
for i in list_from_user_str:
print(count, i) if len(i) <= 10 else print(count, i[:10])
count += 1
|
months_list = ["январь", "февраль", "март", "апрель", "май", "июнь", "июль", "август", "сентябрь", "октябрь", "ноябрь",
"декабрь"]
months_dict = {1: "январь",
2: "февраль",
3: "март",
4: "апрель",
5: "май",
6: "июнь",
... |
n = input("Введите целое положительное число: ")
my_sum = int(n) + int(n * 2) + int(n * 3)
#print(my_sum) |
specs = {"название": None, "цена": None, "количество": None, "eд": None} # тут мог быть список, но хотелось потренить словари)
goods = []
for i in range(int(input("Введите целое положительное количество товаров: "))):
item_num = i + 1
item_specs = {}
for spec in specs:
item_specs[spec] = input(f... |
profit = int(input("Напишите, пожалуйста, доход вашей фирмы в рублях без учёта копеек (не бойтесь, я программист!): "))
costs = int(input("Спасибо! Теперь в той же форме напишите издержки вашей фирмы: "))
real_profit = profit - costs
if real_profit > 0:
print("Вы молодец!")
some_complicated_profit = real_profi... |
# Initialize an array containing the robot's location belief function.
p = [0.2, 0.2, 0.2, 0.2, 0.2]
world = ['green', 'red', 'red', 'green', 'green']
measurements = ['red', 'red']
motions = [1, 1]
# Sensor accuracy
pHit = 0.6
pMiss = 0.2
# Movement accuracy
pExact = 0.8
pUndershoot = 0.1
pOvershoot = 0.1
def sens... |
"""
--- Day 5: Binary Boarding ---
First puzzle answer: 828
Second puzzle answer:
"""
def puzzle2():
"""
puzzle 2
"""
with open("input.txt") as file:
seat_strings = file.read().split("\n")
list_ids = []
for seat_str in seat_strings:
row, seat = find_seat_id(seat_str)
if 0 < row < 127:
list_id... |
import numpy as np
from .arrays import GridBasedArrayDesign
from ..utils.math import unique_rows
def compute_location_differences(locations):
r"""Computes all locations differences, including duplicates.
Suppose ``locations`` is :math:`m \times d`, then the result will be an
:math:`m^2 \times d` matri... |
"""
For part III of this assignment, you'll implement a model from scratch has a vague relationship to the Weiss et al.
ambiguous-motion model. The model will try to infer the direction of motion from some observations.
I'll assume that a rigid motion is being observed involving an object that has two distictinctive v... |
#!/usr/bin/env python
import re
import thread
import itertools
import warnings
import math
def _is_number(s):
if s in ['0', '1', '2', '1000']:
return True
try:
float(s)
return True
except ValueError:
return False
def _starts_with_number(s):
return s[0... |
from copy import *
from random import shuffle
class Strategy:
def __init__(self):
self.BOARD_WIDTH = 7
self.BOARD_HEIGHT = 6
self.AI_PLAYER = 'O'
self.HUMAN_PLAYER = 'X'
def MiniMaxAlphaBeta(self, board, depth, player):
"""
A minimax algorithm[5] is a recursive... |
from src.utils import *
from src.agent import *
class Controller:
"""
The controller class handles the flow of the program
- It creates the agent: The agent class contains methods for creating and revising the belief base
- It contains methods for displaying general information and valid syntax exampl... |
"""CSC111 Project: COVID-19 Contact Visualizer
Module Description
==================
Social Graph Dataclasses Module
This module contains the dataclasses and their methods that represent a network of people.
Copyright and Usage Information
===============================
This file is Copyright (c) 2021 Simon Chen, Pa... |
# -*- coding: utf-8 -*-
#d = {"k1":"v1", "k2":"v2", "k3":"v3"}
#print(d)
# Reihenfolge unbekannt
#e = d.copy()
#print(e)
#d.clear()
#print(d)
### Bereich II ###
### Dictionary wird kopiert
### Aber die Inhalte sind Referenzen
### Hier auf dieselbe Liste
#d1 = {"key" : [1,2,3]}
#d2 = d1.copy()
#d2["key"].append(4)
#p... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Python Beispiele zu
# http://www.thomas-guettler.de/vortraege/python/einfuehrung.html
#
# (c) 2003-2012 Thomas Güttler
# http://www.thomas-guettler.de/
#
# Beispiel ZINSEN:
# Ein Versicherungsvertreter verspricht dir, dass du einen großen
# Betrag bekommst, wenn du 35 Jah... |
# -*- coding: utf-8 -*-
# Unterscheidung fehlt, ob es geschafft wurde oder
# ob das Spiel beendet wurde
# SONDERFALL
# In Python kann man Schleifen mit einem else-Fall
# versehen
geheimnis = 1234
versuch = 0
while versuch != geheimnis:
versuch = int(input("Raten Sie: "))
if versuch > geheimnis:
print("zu gross")
... |
# -*- coding: utf-8 -*-
def func(a, b):
print("Id der Instanz in der Funktion", id(a))
print("Id der Instanz in der Funktion", id(b))
#p = 1
#q = [1,2,3]
#print("Id der Instanz", id(p))
#print("Id der Instanz", id(q))
#print(func(p, q))
# Unsichere Listen
def func1(liste):
liste[0] = 42
liste += [5,6,7,8,9]
#za... |
# -*- coding: utf-8 -*-
class A:
def __init__(self):
self._X = 100
def getX(self):
return self._X
def setX(self, wert):
if wert < 0:
return
self._X = wert
X = property(getX, setX)
# Der Zugriff auf X wird mit Property
# auf die getX und setX Methode gesetzt
# Sie werden automatisch implizit genut... |
import os
import sys
fileList = []
rootdir = sys.argv[1]
for root, subFolders, files in os.walk(rootdir):
for file in files:
fileList.append(os.path.join(root,file))
print fileList
#================================================================================
# List of all the files, total count of file... |
# -*- coding: utf-8 -*-
a = 7
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b) |
# -*- coding: utf-8 -*-
"""
Entspricht einem Delay
"""
import time, threading
def wecker(gestellt):
print("RIIIIIIIIIING!!!")
print("Der Wecker wurde um {0} Uhr gestellt.".format(gestellt))
print("Es ist {0} Uhr".format(time.strftime("%H:%M:%S")))
timer = threading.Timer(30, wecker, [time... |
#! /usr/bin/env python
#coding=utf-8
"""This script generates a random circle wallpaper
Range of values to get from can be adjusted below to create a more artistic wallpaper
based on colour theory"""
from random import randint
# Document size
WIDTH, HEIGHT = (1920, 1200)
circles = []
blurs = []
# Make x number of c... |
# -*- coding: utf-8 -*-
import copy as c
# Echte Kopie
#s = [1,2,3]
#t = c.copy(s)
#print(s is t)
# alles ok und wie erwartet
#liste = [1, [2, 3]]
#liste2 = c.copy(liste)
#liste2.append(4)
#print(liste)
#print(liste2)
# Manipulieren der inneren Liste -> nicht ok
#liste2[1].append(1337)
#print(list... |
import numpy as np
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
para = """A warm welcome to you all.
I am here to deliver a speech on India.
India is one of the ancient civilizations in the world and is also the 7th largest country in the world.
... |
# 34. Find First and Last Position of Element in Sorted Array
import math
class Solution:
def searchRange(self, nums: list, target: int) -> list:
# binary search
left = 0
right = len(nums) - 1
if right == -1:
return [-1, -1]
while left <= right:
mid ... |
# 123. Best Time to Buy and Sell Stock III
class Solution:
def maxProfit(self, prices: list) -> int:
return 1
if __name__ == "__main__":
import time
start = time.clock()
s = Solution()
test_case = 0
ans = s.function(test_case)
print(ans)
end = time.clock()
print('Run... |
# 155. Min Stack
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.size = 0
def push(self, x):
"""
:type x: int
:rtype: None
"""
if self.size and x > self.stack[self.si... |
# 114. Flatten Binary Tree to Linked List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-pl... |
# 988. Smallest String Starting From Leaf
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
min_str = 'z' * 1000
def smallestFromLeaf(self, root)... |
# 215. Kth Largest Element in an Array
class Solution:
def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int':
low = 0
high = len(nums) - 1
k = len(nums) - k
while low < high:
pivot = self.partition(nums, low, high)
if pivot > k:
high ... |
# 448. Find All Numbers Disappeared in an Array
class Solution:
def findDisappearedNumbers(self, nums: 'List[int]') -> 'List[int]':
for i in range(len(nums)):
while nums[i] != i + 1 and nums[nums[i] - 1] != nums[i]:
tmp = nums[i]
nums[i] = nums[nums[i] - 1]
... |
# -*- coding: utf-8 -*-
print "I will now count my chickens:"
print "Hens", 25 + 30 /6
# %is qiuyu
print "Roosters", 100 - 25 *3 % 4
print "Now i will count the eggs:"
print 3 + 2 + 1- 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3+2<5-7?"
print 3 + 2 < 5 - 7
print "oh, that's why it's False."
print "How about ... |
# coding: utf-8
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "The numbers: "
for num in numbers:
print num
#testing
a = 0
variables = 10
use = 2
lists1 = []
while a < variables:
print "At the top a... |
"""
Answer to https://adventofcode.com/2018/day/6
"""
from typing import List
from collections import namedtuple
class Point(object):
def __init__(self, x: int, y: int, map=None):
self.x = x
self.y = y
self.map = map
def __str__(self):
return '(%d, %d)' % (self.x, self.y)
... |
import re
from file_converter.column_types import DATE_TYPE, NUMERIC_TYPE, STRING_TYPE
class ValueFormatter:
"""
Factory to return a ValueFormatter class corresponding to each type of data
"""
@staticmethod
def validate_format(data_value):
pass
@staticmethod
def convert(data_valu... |
#snakeEyes.py
#Will Schick
#5/8/2018
#Driver module that uses the Die class to repeatedly roll two dice until snake eyes are rolled.
#Imports
from die import Die
def main():
#Declare our dice
die1 = Die()
die2 = Die()
#init (Randomizes our face values)
die1.roll()
... |
#stringProcessing.py
#Will Schick
#8:37 - 4/9/2018
#
#
## RETURNS THE LOCATION OF THE FIRST DIGIT. -1 if no digits --------------------------------------------------
def firstDigit(string):
i = 0
while i < len(string):
if string[i].isdigit():
return i
#Update... |
from temp import Temperature
def main():
temp1 = Temperature()
#Test Getters
print("Testing getCelsius() and getFahrenheit().")
print("Celsius temperuture should be 0.00 and is %.2f" % temp1.getCelsius())
print("Fahren. temperature should be 32.00 and is %.2f" % temp1.getFahrenheit())... |
# stringThings.py
#
# Created by: R. Givens
# Modified by: Will Schick on 4/10/2018 @ 1:41 PM
#
# Module containing several functions that process strings.
##Loop through the indices and count the amount of digits
def countDigits(string):
i = 0
digitCount = 0
while i <= (len(string) -... |
#gameOfNim.py
#Will Schick
#3/22/2018
from math import *
from random import *
#Contents--------------------------------------------------------------------------
#Constants
#Welcome player
#Randomly choose amount of sticks
#Randomly choose who goes first
#Loop ( Gameplay )
#Player who drew the last stick... |
class BST:
'''Represents a binary search tree'''
def __init__ (self, head=None):
'''initialize the BST'''
#None
#|
#head
#/ \
#None None
self.tree = [None,head,None,None]
def left_of(self, index):
'''get index left of curr... |
'''平方根格式化
描述
获得用户输入的一个整数a,计算a的平方根,保留小数点后3位,并打印输出。
输出结果采用宽度30个字符、右对齐输出、多余字符采用加号(+)填充。
如果结果超过30个字符,则以结果宽度为准。'''
a=input... |
if __name__ == '__main__':
n = int(input())
number = ""
if 1 <= n <= 150:
x = 1
while x <= n:
print(x, end="")
x += 1
else:
print("Enter the number between 1 to 150")
|
"""
Course: EE2703-Applied Programming Lab
Name: Nihal Gajjala
Roll Number: EE19B044
Assignment 1
"""
from sys import argv, exit
# Assigning Constant Variables
CIRCUIT='.circuit'
END='.end'
# Validating The Number Of Arguments
if len(argv)!=2:
print('\nUsage: %s <inputfile>' %argv[0])
exit()
# Validating The Fi... |
"""
Course: EE2703-Applied Programming Lab
Name: Nihal Gajjala
Roll Number: EE19B044
End Semester Exam
"""
# Importing Libraries
import numpy as np
import pylab
# Function To Calculate Rijkl
def calc(l):
return np.linalg.norm(np.tile(rijk,(100,1,1,1)).reshape((100,3,3,3,1000))-np.hstack((r_vector,np.... |
#How to read a text file from Hard Disk
#test.txt file is already there in current dir
fileObj = open("test.txt")
'''FileNotFoundError:
[Errno 2] No such file or directory: 'test1.txt'
'''
#read a file content
data = fileObj.read()
print("File Content: ", data)
print('\n\n')
print(open('../t... |
'''(Replace text) Write a program that replaces text in a file. Your program should prompt the user to enter a filename, an old string, and a new string. Here is a sample run:
Enter a filename: test.txt
Enter the old string to be replaced: morning
Enter the new string to replace the old string:
afternoon
'''
... |
#import csv module
import csv#read the file in r mode
f = open("students.txt", "r")
#csv.reader() takes delimiter
readercsv = csv.reader(f, delimiter='\t')#iterate the content
for line in readercsv:
print(line)
|
board = {'7': ' ' , '8': ' ' , '9': ' ' ,
'4': ' ' , '5': ' ' , '6': ' ' ,
'1': ' ' , '2': ' ' , '3': ' '}
player_list = {"player 1":"X", "player 2":"O"}
#track who is the current player
current_player = "player 1"
def change_player(curr_player):
global current_player
if curr_player == "pla... |
import math
relative = 0
for i in range(1,479001599 ):
#print(i,":",end="")
#print ("The gcd of 21 and ",i," is : ",end="")
#print (math.gcd(21,i),end="")
if(math.gcd(21,i) == 1):
#print(" this is relative")
relative += 1
else:
pass
#print()
print("ϕ(n) = ",relative) |
#Hackerrank Challenge
#Given five positive integers, find the minimum and maximum values
#that can be calculated by summing exactly four of the five integers.
def miniMaxSum(arr):
arr.sort()
print(sum(arr[:4]), sum(arr[1:]))
def miniMaxSum(arr):
print(sum(arr)-max(arr),end=" ")
print(sum(arr)-min... |
#method
list=[1,2,3]
list.append(4)
list.pop()
print(type(list))
print(list)
myString= 'Hello'
print(myString.upper())
print(type(myString)) |
website = "www.sadikturan.com"
course= "Phyton Kursu: Baştan Sona Phyton Programlama Rehberiniz(40 saat)"
#1- 'course' karakter diisinde kaç karakter bulunur?
'''length= len(course)
print(length)'''
#2- 'website' içinden wwww karakterlerini alın.
'''result=website[0:3]
print(result)'''
#3- 'website' içinden com karakt... |
'''sayilar=[1,3,5,7,9,12,19,21]'''
#1-Sayılar listesindeki hangi sayılar 3'ün katıdır?
'''for i in sayilar:
if i%3==0:
print(i)'''
#2-Sayılar listesindeki sayıların toplamı kaçtır?
'''sum=0
for i in sayilar:
sum+=i
print(sum)'''
#3-Sayılar listesindeki tek sayıların karesini alın.
'''for s in sayilar:
... |
def not_hesapla(satir):
satir= satir[:-1] #satır aalarındaki boşluğu kaldırdık
liste= satir.split(':')
OgrenciAdi=liste[0]
notlar=liste[1].split(',')
not1= int(notlar[0])
not2= int(notlar[1])
not3= int(notlar[2])
ortalama= (not1+not2+not3)/3
if ortalama>=90 and ortalama<=100:
... |
list=[1, 2, 3]
tuple=(1, 'iki', 3)
"""print(type(list))
print(type(tuple))
print(list[2])
print(tuple[2])
print(len(list))
print(len(tuple))"""
#listelerde karakter değişikliği yapılabilir ama tuple larda değişiklik yapılamaz
list=['Damla', 'Ayşe']
tuple=('Ali', 'Veli', 'Ayşe', 'Ayşe')
names=('Hatice', 'Pınar', 'Eli... |
#Inheritance (Kalıtım): Miras alma
#Person => name, lastname, age, eat(), run(), drink()
#Student(Person), Teacher(Person)
#Animal=> Dog(Animal), Cat(Animal)
class Person():
def __init__(self, fname, lname):
self.firstName=fname
self.lastName=lname
print('Person Created')
def who_am... |
#class
class Person:
# pass #yer tutar, kodun hata vermeden devamını sağlar
#class attributes
adress='no information'
#constructur
def __init__(self,name,year):
#object attributes
self.name= name
self.year= year
#methods
#object,instance
p1= Person('Pınar',1995)
p2=P... |
from abc import abstractmethod, ABC
from typing import Any, Iterable
class BaseTextPreprocessor(ABC):
""" Abstract class for base text explainer """
@abstractmethod
def build_vocab(self, text: str):
"""Build the vocabulary (all words that appear at least once in text)
:param text: a list... |
from urllib import request
from bs4 import BeautifulSoup as bs
import re
import nltk
import heapq
def text_summarizer(input, max_sentences):
sentences_original = nltk.sent_tokenize(input)
# if (max_sentences > len(sentences_original)):
# print("Error, number of requested sentences exceeds number of sen... |
import numpy as np
def newton_multivar(fun,var,xi,tol=1.0e-12,maxiter=100000):
""" Multivariate Newton root-finding using automatic differentiation.
INPUTS
=======
fun: an autodiff Operation or Array object whose roots are to be computed.
var: an array of autodiff Var objects that are independent... |
# Set the initial state
# Tile A has value 1, B has value 2, C has value 3, agent has value 4 and the rest blank tiles have value 0
initial_state = [1, 0, 0, 0, 4, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0]
# Set the goal state
goal = [0, 0, 0, 0, 4, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0]
# Create a class for initializing a node
# Th... |
from sys import argv
script, filename = argv
txt = open(filename)
print("Here's your file %r" %filename)
print(txt.read())
txt.close()
print("Type the filename again:")
filename_again = input(">")
txt_again = open(filename_again)
print(txt_again.read())
txt_again.close() |
def print_two(*args):
arg1, arg2 = args
print("arg1: %r, arg2: %r" %(arg1, arg2))
def print_two_again(arg1, arg2):
print("arg1: %r, arg2: %r" %(arg1, arg2))
def print_one(arg1):
print("arg1: %r" %arg1)
def print_none():
print("none")
print_two("a", "b")
print_two_again("a", "b")
print_one('aaa')
print... |
class User:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def withdrawl(self,amount):
self.balance -= amount
print (self.name,self.balance)
return self
def deposit(self, amount):
self.balance += amount
print (f'{s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.