blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
ed40ca05902438e6576b31dd39dde08899ac8a53
adefisayoA/python_class
/flow_control.py
1,857
4.375
4
# conditional statements (if, elif, else), # loops (for, while). # # # if statement # # if <expr>: # # <statement> # one way logic # else: # <statement> # this is the option to take # if x > y: # print(f"{x} is greater than {y}") # else: # print(f"{x} is less than {y}") # # # rich man, good man,...
3c031790f24382640a53475a171f6e6b9ac290aa
wzog99/etf_hypothesis_testing
/test_statistics.py
1,799
3.515625
4
import statistics import scipy.stats as stats import math import numpy as np def calculate_test_stats(avg_pct_index1, avg_pct_index2): ''' Function to calculate the Z-statistic of a sample mutual fund index compared to its benchmark index (population) as well as a p-value for the same two indices Inpu...
b800f1a845f6e86de56265d9b763d0334f60d2d3
lphan13/UVA-artificial-intelligence
/eight-puzzle/eightpuzzle.py
8,297
4.0625
4
#Lauren Phan and Chun Tseng from random import * from collections import deque import copy # python program to generate a random 8-puzzle board, determine if it is solvable, and find a solution to the goal state #puzzleBoard class consisting of children, parent, current grid configuration, # of inversions class puzzl...
0d170ba2487cd00ba20f575b5d49a0834693bef9
prositen/advent-of-code
/python/src/y2016/dec21.py
6,244
3.796875
4
import re class Scrambler(object): re_SWAP_POSITION = re.compile(r'swap position (\d+) with position (\d+)') re_SWAP_LETTER = re.compile(r'swap letter (\w) with letter (\w)') re_ROTATE_LEFT = re.compile(r'rotate left (\d+) steps?') re_ROTATE_RIGHT = re.compile(r'rotate right (\d+) steps?') re_ROTA...
051837adbfcbd0d06658fe53fb00b5e7bf54c2b4
RDee26/nbgrader
/createFiles.py
627
3.921875
4
import os # Python program to explain os.mkdir() method # path assignmentPath = './assignments' nbgraderPath = './nbgrader/submitted' try: os.mkdir(assignmentPath) except OSError as error: print(error) try: os.makedirs(nbgraderPath) except OSError as error: print(error) studentCount = int(input("Enter number...
185c5d7e8b826b3f1578c40faa5b6720bb76f421
SLPeoples/BBIO-393-Computational-Biology
/Meeting12/random_network.py
8,375
3.59375
4
from __future__ import division """ This script simulates a random biological network and includes code for NetworkNode objects """ from random import random from copy import copy from numpy.random import choice import matplotlib.pyplot as plt from numpy import linspace class NetworkNode(object): """A network n...
a4fcb6971f71f02a752e7b4100b1599995fef7c2
alexandraback/datacollection
/solutions_5756407898963968_0/Python/AdamJB/trick.py
822
3.578125
4
#!/usr/bin/env python def findCard(guesses, cards, case): firstGuessRow = cards[0][guesses[0]-1] secondGuessRow = cards[1][guesses[1]-1] numValueIsEqual = 0 foundValue = 0 for first in firstGuessRow: if first in secondGuessRow: foundValue = first numValueIsEqual += 1 value = str(foundValue) if numValu...
ea473d930e3c5899c97d5dd41c289bb6131bdf42
pirhoo/python-course-fr
/teaching-demos/08.py
275
3.640625
4
# coding: utf-8 """ Exercise: write an email """ first_name = "gustaf" last_name = "fridolin" domain = "riksdagen.se" email = first_name + "." + last_name + "@" + domain print(email) # Alternative: string replacement email = "%s.%s@%s" % (first_name, last_name, domain)
14c6355887173fb18a2fe49ba0b657e73527ae79
leyulin/CS550
/A2/npuzzle.py
1,336
3.671875
4
""" Created on Feb 23, 2020 @author1: leyu_lin(Jack) @author2: Parth_Thummar """ from basicsearch_lib02.searchrep import Problem from basicsearch_lib02.tileboard import TileBoard class NPuzzle(Problem): """ NPuzzle - Problem representation for an N-tile puzzle Provides implementations for Problem action...
498d171bf9797edf657675f78a85105f68c7e342
MurphyMarkW/random
/python/examples/properties.py
449
3.578125
4
#!/usr/bin/env python3 class Test(object): @property def var(self): print('Property called.') return self._var @var.getter def var(self): print('Getter called.') return self._var @var.setter def var(self,val): print('Setter called.') self._var = val @var.deleter def var(self)...
e804047fa4759eb3e9f6a6a1b362d58f9060d081
tikipatel/LL-AdvancedPython
/Chapter 4/ordered_dict.py
2,157
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 18 22:31:27 2020 @author: pratikbhaipatel """ from collections import OrderedDict, namedtuple def main(): # list of sports teams with wins and losses ScoreTracker = namedtuple('Score', 'wins losses') sports_teams = [ ('Royals'...
e8cb13992441e52a5434b0376f2c1a9e82453c84
proTao/leetcode
/1. backtracking/037.py
4,172
3.859375
4
import time from random import randint from pprint import pprint USE_HUMAN_EXPERIENCE = True class Solution: def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ if USE_HUMAN_EXPERIENCE: ...
c25edaf21b3e5053c8f8dd70eb5ed507207abfc4
elinwub/INF200-2019-Exercises
/src/elin_bjoernson_ex/ex02/message_entropy.py
642
3.75
4
# -*- coding: utf-8 -*- from collections import Counter import math def letter_freq(txt): return Counter(txt.lower()) def entropy(message): # make a dictionary for letters and letter count letters = letter_freq(message) # calculate frequency for every letter in message frequency = [letters[chara...
394054a1cf6728f394e088e604a4d78ca2e09296
MaartenvEijck/TICT-V1PROG-15
/Les 04/Oefening 4_3.py
139
3.765625
4
def swap(lst): if len(lst)> 1: lst[0], lst[1]= lst[1], lst[0] return lst lst = [1,2,3,4] res = swap(lst) print(res)
2dd534614f0e1e2b17056fb285191c214d005b19
farhan85/Misc
/python/custom_iter.py
1,174
3.765625
4
#!/usr/bin/env python3 class Team(object): def __init__(self, members=None, staff=None): self.members = list(members) if members is not None else [] self.staff = list(staff) if staff is not None else [] def __iter__(self): return TeamIterator(self) class TeamIterator(object): def...
efa9a4dbaac8fb49a8b54606c01cc08f22cdd650
andrewbells/python_learning
/coursera/populate_dict.py
948
4.03125
4
'''The program extracts values of student number and grade from a .txt file (grades_program.txt) and creates a dictionary using these values''' import tkinter.filedialog def main(): grade_file = open(tkinter.filedialog.askopenfilename()) print (read_grades(grade_file)) grade_file.close() d...
f68f8084f7858717868f447209c1912692c10b12
mengshixing/Django
/python3 note/chapter 12 常用内建模块/_collections.py
3,388
3.921875
4
#collections集合模块 #namedtuple是一个函数,用来创建tuple对象 #并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素 point=(2,3) print(point) from collections import namedtuple Point=namedtuple('_Point',['x','y']) p=Point(2,4) print(p.x,p.y) print(isinstance(p, Point)) print(isinstance(p, tuple)) # namedtuple('名称', [属性list]): # Cir...
2631ffba2ec0da11426c9f013280228a9683ffc0
rdsrinivas/python
/list-pmp.py
661
4.3125
4
#!/usr/local/bin/python """ Practice Makes Perfect Great work! See? This list slicing business is pretty straightforward. Let's do one more, just to prove you really know your stuff. Instructions Create a list, to_21, that's just the numbers from 1 to 21, inclusive. Create a second list, odds, that contain...
c82f6cbb8f6ebdb424b970c92408cd022046ab0a
marceloigor/ifpi-ads-algoritmos2020
/Fabio01_Parte01/q2 horas e minutos equivalente em minutos.py
395
3.75
4
# 2. Leia um valor em horas e um valor em minutos, # calcule e escreva o equivalente em minutos. # Entrada valor_horas = int(input('Digite um valor em horas: ')) valor_minutos = int(input('Digite um valor em minutos: ')) # Processamento equivalente_minutos = valor_horas * 60 + valor_minutos # Saída print(f'{valor_h...
d851a72aa7d67c94321ac028d3a10dace4dc904c
yingxingtianxia/python
/PycharmProjects/nsd_python_v02/nsd_python_d06/d6-12.py
590
3.8125
4
#!/usr/bin/env python3 #--*--coding: utf8--*-- from random import randint from functools import reduce def func1(num): return num % 2 def func2(num): return num * 2 def func3(x, y): return x + y if __name__ == '__main__': num_list = [randint(1, 100) for i in range(10)] print(num_list...
039df7fbdb986ab89067838113194f6123024db0
neu-velocity/code-camp-debut
/codes/AndrewSun/0098.py
560
3.671875
4
class Solution: def isValidBST(self, root: TreeNode) -> bool: # top-down recursion def recursion(node, lower = float('-inf'), upper = float('inf')): if not node: return True if node.val <= lower or node.val >= upper: return Fal...
ccd42c85f42134ea3d5e8d8dbc92eb8fef6390fd
Banzaci/python
/p.py
785
3.65625
4
# x = 0 # while x < 10: # print(x) # x = x + 1 # x = int(input('Enter a number: ')) # if x < 0: # x = 0 # print('Negative') # elif x == 0: # print('Zero') # else: # print('Positive') # pets = ['dog', 'cat', 'mouse'] # for pet in pets: # print('I have a {0}'.format(pet)) # for i in range(10, 0, -1):...
9bd2bec14a26a0fc576eb8e75dfde7a2f53a29f8
emnharris/COSC-1336
/conversion_rate_program/conversion_rate_program.py
1,605
3.90625
4
import convert MI_MEASURE = 'miles' GAL_MEASURE = 'gallons' TEMP_MEASURE = 'degrees' LB_MEASURE = 'pounds' INCH_MEASURE = 'inches' def run_program(): convert.intro() mi = float(input('Miles: ')) unit = MI_MEASURE valid, mi = convert.validate_neg(mi, unit) if valid: km = convert.run_convers...
c8916359d824e2eae75323bc166d5fd4c73b5499
kiana-kh/pyProject
/appendcategory.py
2,594
4.09375
4
categories = ["Bills","Cleaning","Elevator","Parking","Repairment","Charge"] subcategories = {"Bills":["Water","Electricity","Gas","Tax"]} def category_input(categories,subcategories): loop = True while(loop): try: print("please enter the category or its number f...
b53a01dfed909edc0c12ee3d42e653cfc4869e27
topliceanu/learn
/python/algo/src/random_algorithms.py
697
3.71875
4
# -*- coding: utf-8 -*- import random def fisher_yates(arr): """ Random shuffle of input array. """ for i in range(len(arr)): j = random.randrange(0, i) arr[i], arr[j] = arr[j], arr[i] return arr def reservoir_sampling(generator, k): """ Pick at random k element from arr. """ sa...
a6d21ad253db219f27cd64c2a3b5ed56c0dd8870
whisperH/AlgorithmsAndMeachineLearning
/Tree/BST.py
5,583
3.890625
4
''' 二叉排序树 ''' class BSTNode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def __delete__(self): print('free BSTNode') class BSTree: def __init__(self): self.root = None def isEmpty(self): if self....
8ddd5ab9902a20d78d27801c6f1232f1c2fefaa6
zhyordanova/Python-Fundamentals
/08-Text-Processing/Exercise/03_extract_file.py
176
3.75
4
text = input().split("\\")[-1] file_name = text.split(".")[0] file_extension = text.split(".")[1] print(f"File name: {file_name}") print(f"File extension: {file_extension}")
2444f7d0453d67b9057034c05b26ddfcc2472f43
jpalisoul/CS301-Algorithms
/Assignment 2 - Search Algorithm Analysis/PalisoulJosephSearchTester.py
2,174
3.671875
4
######################################################################### # Assignment 2 - Searching Algorithms (Tester) # # # # PROGRAMMED BY Joe Palisoul (January 22, 2015) # # CLASS CS30...
a00c50704596afe95c4735eda1e60358c7cf8719
ricardoleoncorreia/code-challenge-magoya
/recursive-digit-sum.py
1,085
3.71875
4
""" This medium difficulty exercise was taken from https://www.hackerrank.com/challenges/recursive-digit-sum/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=recursion-backtracking """ def superDigit(n, k): """ Returns the superdigit of the number n repeated k times...
218b30076760589621baca703f0a3c776e925e5d
joshualeejunyi/Programming-Fundamentals
/Lab 3/count.py
1,672
4.03125
4
import sys def counter(string): alphadict = {} for alphabet in string: if alphabet != ',': if alphabet not in alphadict: alphadict[alphabet] = 1 else: alphadict[alphabet] = alphadict[alphabet] + 1 return alphadict # so the brief says to hav...
5a07f2923e67b9233fd0c136c3cde4c41307d4f4
eMUQI/Python-study
/python_book/basics/chapter05_if/05-05.py
251
3.765625
4
alien_color = "green" # alien_color = "red" # alien_color = "yellow" if alien_color == "green": print("You got 5 point ! ") elif alien_color == "yellow": print("You got 10 point !") elif alien_color == "red": print("You got 15 point !")
4db7933e9ce9aebe7f286b78306230365a504240
rahcosta/Curso_em_Video_Python_3
/Parte 2/7. REPETIÇÃO FOR.py
215
3.9375
4
for c in range(6, -1, -1): print(c) print('FIM') #inicio = int(input('Início: ')) #fim = int(input('Fim: ')) #passo = int(input('Passo: ')) #for i in range(inicio, fim + 1, passo): # print(i) #print('FIM')
df6d5269ce0e853b072bce6005113c2d71dc9341
codebubb/python_course
/Semester 1/Project submissions/Andreas Georgiou/Semester 1 - Introduction to Programming/Semester 1 - Introduction to Programming/Week 1/Python_Practise/try except practice.py
668
4.15625
4
while True: try: number = int(raw_input("Enter a number: ")) print number break except ValueError: #(ValueError, IOError): list of exceptions in parentheses (), separated by commas print "That is not a number." try: with open('file.txt', 'r') as f: print int(f.readline())...
4097e3f7d9c04b12874d97f131ec72cb0229d688
pmatysek/Advent-of-Code
/day1.py
279
3.875
4
from itertools import cycle, accumulate def input(): return map(int, open("day1.txt")) print(sum(input())) frequencies = set() for frequency in accumulate(cycle(input())): if frequency in frequencies or frequencies.add(frequency): print(frequency) break
c748d1b278f3768f01f6b2030b69af5ee9e992cd
CyborgVillager/Gui_Tutorial
/tkint_tutorial_files/tkint_version0/kill_question.py
732
3.828125
4
from tkinter_source_file import * # Acquired from https://www.daniweb.com/programming/software-development/threads/66698/exit-a-tkinter-gui-program # Other options if a user would like to shut down the program. # Will look further into this to make the program more interactive and to help aid in A.i development as well...
92b288633e9105bf3cdf5dc55fbda1550b185512
nathrichCSUF/Connect4AI
/ai.py
2,578
3.578125
4
import copy from board import Board class AI: def minimax(self, board, depth, bestVal, minVal, isMaxiPlayer): val = 0 r = 0 column = 0 validLocations = board.getValidLocations() is_gameTerminal = board.gameFinished() if depth == 0 or is_gameTerminal: if i...
6c4e3d7719deeba77e04526d7e4b028e81f88b21
TakehikoEsaka/selenium_docker
/docker_for_debug/tests/wait.py
1,544
3.53125
4
# 必要なライブラリのインポート import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver import DesiredCapabilities # ChromeのDriverを使ってseleniumHubにアクセスしdriver取...
74aa5c1335f234f790edde3b15ad02de108e1193
AhrCode/cursoBasicoDePython
/multiples_of_3_or_5.py
488
3.953125
4
def solution(number): if number < 0: return 0 else: list = [] sum = 0 for i in range(number): list.append(i) for i in range(number): if list[i]%3 == 0 or list[i]%5 == 0: sum = sum + i return sum def run(): number = ...
643e6433dc0d7d6a3f0381a232c2039f77944cf2
PedroSantos42/python-exercises
/curso-em-video/mundo-1/Desafio023.py
277
3.578125
4
n = int(input('Insira um número entre 0 e 9999: ')) print('Unidade: {} \n' 'Dezena: {} \n' 'Centena: {} \n' 'Milhar: {}'.format(n%10, (n//10)%10, (n//100)%10, (n//1000)%10))
4539644fb97f958fd119a5c3022c6dbc0e9323e9
JunIce/python_note
/note/note_14.py
3,716
3.515625
4
#!/usr/bin/python #coding=utf-8 ''' 正则表达式 Python通过re模块提供对正则表达式的支持。使用re的一般步骤是先将正则表达式的字符串形式编译为Pattern实例,然后使用Pattern实例处理文本并获得匹配结果(一个Match实例),最后使用Match实例获得信息,进行其他的操作。 . 代表任意字符 | 逻辑或操作符 [ ] 匹配内部的任一字符或子表达式 [^] 对字符集和取非 - 定义一个区间 \ 对下一字符取非(通常是普通变特殊,特殊变普通) * 匹配前面的字符或者子表达式0次或多次 *? 惰性匹配上一个 + 匹配...
e09fc1c7230dad6c8a0371f9e732add42437801b
akshaymoharir/PythonCrashCourse
/chapter_6/ex_6-4.py
1,223
4.25
4
## Python Crash Course # Exercise 6.4: Glossary#2: # Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102) # by replacing your series of print statements with a loop that runs through the dictionary’s keys and values. # Whe...
1c0c42a5c7cef72a6470053d3cc0d847caa87d2a
JayKay24/coding_challenges
/common-sense-guide-data-structures-and-algorithms/optimizing_for_optimistic_scenarios/insertion_sort.py
342
4.125
4
def insertion_sort(array): for index in range(1, len(array)): temp_value = array[index] position = index - 1 while position >= 0: if array[position] > temp_value: array[position + 1] = array[position] position = position - 1 else: break array[position + 1] = temp...
3ac2360a2e3b4243e18fcd3d89f22e14a44604cf
ml758392/python_tedu
/nsd2018-master/nsd1804/python/day06/fracial.py
392
3.671875
4
def func(x): # 递归函数,自己再调用自己 if x == 1: return 1 return x * func(x - 1) # 5 * func(4) # 5 * 4 * func(3) # 5 * 4 * 3 * func(2) # 5 * 4 * 3 * 2 * func(1) # 5 * 4 * 3 * 2 * 1 if __name__ == '__main__': print(func(5)) print(func(6)) # 5!=5X4X3X2X1 # 5!...
3e194d8dfa0960482896ba0855bb30987ae20eb6
Robock/project-compass
/how_many_snakes.py
2,855
3.84375
4
''' headlines = ["Papperbok Review: Totally Triffic", "Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away" ] news_ticker = "" #ticker...
a974a054a6fe8cb73436f510aed39536efcb766c
UCB-INFO-PYTHON/WorkWitch_JDunn
/interface.py
17,495
3.96875
4
import time import assets class Window: """ This is a class that represents a window in the terminal screen that will display game information. Attributes: MAX_HEIGHT (int): Class attribute, the maximum height of the terminal screen MAX_WIDTH (int): Class attribute, the maximum width of ...
c4b1b6399f36fd520456003251a2d2b6b09e8adb
goldginkgo/LintCode
/solution/search-for-a-range.py
1,954
3.59375
4
############################################################################### """ Question: LintCode: http://www.lintcode.com/en/problem/search-for-a-range/ Given a sorted array of n integers, find the starting and ending position of a given target value. If the target is not found in the array, return ...
be8810a49f2103a059160fd42dd4c5afeac3a1dc
TripleChoco/ubb
/sem2/Algoritmica Grafelor/practical work no. 4/digraph/digraph.py
5,009
3.59375
4
class DiGraph: def __init__(self, vertices, outEdges, inEdges, viz, isDag): ''' :param vertices: the key is a vertex v, the value is a list of tuples (u, c) with the meaning that there is an edge from v to u of cost c ...
8da737fcbd7e93eb7fc268571f338c55afecc2c4
stuncyilmaz/Word2Vec_MovieReviews
/tfidf_bagOfWords/text_processing.py
1,789
3.609375
4
from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer import nltk import re def negate_words(mystring): numProcessed = 0 mynegation=[] entry={} entry['words']=mystring.split() modifier = None negativeTerritory = 0 for j in range(len(entry["words"])): word...
957ba76c2700760e82e96b037c86266abeedda8d
sorrowfeng/python
/猜数游戏.py
326
3.71875
4
import random daan=random.randint(1,10) print("猜数游戏") temp=input("请输入一个数字:\n") guess=int(temp) while guess != daan : temp=input("猜错了,重新输入:\n") guess=int(temp) if guess > daan : print("大了") else: print("小了") print("猜对了") print("游戏结束")
75ca0104b55e6d9eb0e12291f92daeb447cae977
lovepurple/PythonStudy
/Study/PythonSingleton.py
462
3.96875
4
# -*- coding: utf-8 -*- #Python 里的单例写法,基于decorator #cls 的意思是,使用的是Class.Method() 约定的写法 def singleton(cls): instances = {} def wrapper(): if cls not in instances: instances[cls] = cls() return instances[cls] return wrapper #@singleton class myclass: def __init__(self): self.num = 0 myclass = singleton(m...
750f092673629f581cb1f49eaa48da7c90134673
Aparna-2000/-PESU-IO-SUMMER
/binary_search.py
333
3.71875
4
a=[1,2,3,4,5] ele=4 low=0 high=len(a)-1 mid=int((low+high)/2) pos=-1 while(low<high): mid=int((low+high)/2) if(a[mid]==ele): pos=mid+1 elif(a[mid]<ele): low=mid+1 else: high=mid-1 if pos==-1: print("Number is not found") else: print(ele,"is present at pos...
d50ddbc71f514f2b50cb1eb733d5f271d1092b93
sudheerchalla/Python-Code
/dynamicFibo.py
285
3.671875
4
previous={0:0,1:1} def fibo(n): if n in previous.keys(): return previous[n] else: newValue=fibo(n-1)+fibo(n-2) previous[n]=newValue return newValue print(fibo(4)) print(previous)
53b6b8107c008859d5192a7112ea0488e85995d2
shahamish150294/LeetCode
/ReverseKGroupsLL.py
906
3.609375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseKGroup(self, head, k): first_of_first = ListNode(0) pre = first_of_first pre.next = head curr = head ...
3aa96d0276d8cb16da8189886e7c8db4354219f7
Diwas-Acharya/Code_for_fun
/application_using_python/weather_app . py.py
1,304
3.59375
4
from tkinter import * import requests import json win = Tk() win.geometry("300x400") win.resizable(False , False) City_name = StringVar() disp_msg = StringVar() def get_details(): Name = City_name.get() apikey = "125527c209392a558655eb67c62a193f" try: url = f"http://api.openweathermap.org/data/2.5/weather?q={Na...
f78641469db0bca5943e15cc97c48b262cd1723a
Duvarc/Blue-Dress-Capital
/stocks/random_stock.py
826
3.515625
4
import csv import random stocks = [] with open('all_stocks.csv') as csvfile: reader = csv.reader(csvfile) for row in reader: stocks.append(row) def pick_random(year='d', sector='d', industry='d'): lst = stocks if year != 'd': lst = list(filter(lambda x: x[2] == year, lst)) if sector != 'd': lst = list(fil...
189030977976463acac7db20a8e57d348633db1a
Horse1/Rosalind
/replace.py
170
3.703125
4
s=str(input()) a=s.replace('G','g').replace('C','c').replace('c','G').replace('g','C').replace('A','a').replace('T','t').replace('a','T').replace('t','A') print(a[::-1])
e4dd99286c540c7db3e7852f2dc66d25d0a339ef
codingdojotulsajanuary2019/kunle
/Python_stack/python/fundamentals/function_imm.py
540
3.875
4
import random def randInt(min="", max=""): num = random.random() return num print(randInt()) import random def randInt(min="", max=""): num = random.random() * "max" return num print(randInt(max=50)) import random def randInt(min="", max=""): num = random.random() * "min" return num print(rand...
7c0a47ad7bf9508a1a86ae796412575e51cefe91
fanzeyi/sentencize
/original.py
1,740
3.796875
4
""" Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. """ import random def is_ascii(c): return ord(c) < 128 def is_seperator(c): return c in [" ", ",", "。", ",", ";",...
be5c67c22edb6ae90c6433816e3a0c7b9155652d
250mon/CodeWars
/5_RGBtoHexConversion.py
645
3.53125
4
# >>> n = 255 # >>> f"{n:#x}" '0xff' # >>> f"{n:#02x}" '0xff' # >>> f"{n:#03x}" '0xff' # >>> f"{n:x}" 'ff' # >>> f"{n:0x}" 'ff' # >>> f"{n:03x}" '0ff' # >>> f"{n:04x}" '00ff' # >>> f"{n:4x}" ' ff' # >>> f"{n:*^9x}" '***ff****' def rgb(r, g, b): result = [] for n in (r, g, b): ...
74755010d78520e8785dad87970aa3a757308d10
chen-min/learningPython
/ten/c8.py
1,389
3.71875
4
#概括字符集 # 概括字符集 # \d \D # . 匹配除换行符之外所有其他字符 import re # a = 'python123java456php' # r = re.findall('[0-9]', a) # # r = re.findall('\d', a) # # \w 把数字和字母全部匹配出来 # print(r) # import re # a = 'python 11\t234242&\n' # # \w 只匹配数字及字母, &等符号不能匹配 # # \w用字符集表示 [A-Za-z0-9_] --> \W 匹配除数字和字母外的内容 # # \s 匹配空格、 制表、换行等空白字符 # # \S 非空...
eacfeeb8d98231e678426a188a1d63f64023e534
nekapoor7/Python-and-Django
/GREEKSFORGREEKS/Basic/simple_interest.py
164
3.578125
4
#Python Program for simple interest def simple(p,r,t): SI = (p*r*t)/100; return SI p = int(input()) r = int(input()) t = int(input()) print(simple(p,r,t))
3143b5c8ef51a884692aef9dcaa69618737db2dd
AIHackerTest/chidaozhe_Py101-004
/Chap1/project/wk1.py
1,169
3.734375
4
whether_dict = {} with open('whether_info.txt') as f: for line in f: (key, val) = line.split(",") whether_dict[key] = val print("您将进行一个天气查询程序,如需帮助,请输入h或help。") #建立用户输入查询信息的字典 user_whether_dict = {} while True: order = input("请输入指令或您要查询的城市名:") if order in ["help","h"]: print("\t-输入...
9306e74a701872c19bcca0da6a920ec2bfed5410
aliu2/simulating-aggression
/sim/obj.py
1,099
3.875
4
class Food: def __init__(self): self.consumers = [] def add_consumer(self, organism): self.consumers.append(organism) def get_consumers(self): return self.consumers def num_consumers(self): return len(self.consumers) def __str__(self): return f"{self.cons...
92b1e61d2f01f03d1f0b0c2f0b2d44cbffa4ff49
swq90/python
/designpatterns/singleton2.py
577
3.625
4
#单例模式中懒汉实例化:确保在实际需要时创建一个对象 class Singleton2(object): __instance = None def __init__(self): if not Singleton2.__instance: print("__init__method called..") else: print("Instance already created:",self.getInstance()) @classmethod def getInstance(cls): if not...
7e0a4344fafb450bec67e1eaa899e9fe003a3208
Remus1992/TA_Labs
/day_05/phonebook.py
6,674
3.84375
4
import csv phonebook = { # 'jones': {'first_name': 'Chris', 'last_name': 'Jones', 'phone_number': '5412813629'}, 'Remus': { 'first_name': 'Remington', 'last_name': 'Henderson', 'phone_number': { 'fancy_phone': '(541)281-3629', 'standard_phone': '5412813629' ...
e957041e805085f842047d6cc12cf64b7c3ec559
kothawadegs/learning_python
/practice_gajanan/calculator/BasicPractice/Maths_cal.py
879
4.1875
4
'#class calculator' def add(a, b): "this function adds two numbers" return a + b def subtract(a, b): "this function subtracts two numbers" return a - b def multiply(a, b): "this function multiplies two numbers" return a * b def divide(a, b): "this function divides two numbers" return a / b print ("sel...
aa67413cacdeb6f5b326337c88f7c125750f31ae
adwanAK/adwan_python_core
/think_python_solutions/chapter-18/PokerHand.py
2,288
3.734375
4
"""This module contains code from Think Python by Allen B. Downey http://thinkpython.com Copyright 2012 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from Card import * class PokerHand(Hand): def suit_hist(self): """Builds a histogram of the suits that appear in the hand....
c4f22d48461bdf4da940c956521f8d4b6d602e95
Sheynckes/Machine-Learning
/Classifier Models/scripts/Perceptron.py
2,402
3.546875
4
# -*- coding: utf-8 -*- # @Time : 2018/5/7 23:40 # @Author : SHeynckes # @Email : sheynckes@outlook.com # @File : Perceptron.py # @Software: PyCharm # 使用Python实现感知器学习算法 import numpy as np class PerceptronSimple(object): # 通过使用面向对象编程的方式在一个Python类中定义感知器的接口,使得我们可以初始化新的感知器对象 # 使用类中定义的fit()方法对感知器进行训练,使...
4a488bcf4db321999bc90d45f553105a7b0bf16c
jackedison/tv_show_ratings
/main.py
1,543
3.609375
4
import json # Used to convert json api to python dict import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import seaborn as sbs # Its a wrapper for matplotlib might as well install and make things look nicer import call_api import display def read_in_jsons(json_path, tv_show): '''Read in...
f3387082b24f5c6dcd8cfc50555ac2aa65bc469b
arieljarnason/pa6--
/test4.py
245
3.6875
4
class myobject: def __init__(self, variable1 = None): self.variable1 = variable1 newobject = myobject("blabla") newobject2 = myobject("blabla2") mylist = [newobject, newobject2] mylist.remove(newobject) print(mylist[0].variable1)
7da956474f626bcddba27e5d779b53226a286b8a
zhangpanzhan/leetcode-solution
/20120215 Reverse Nodes in k-Group.py
1,860
4.0625
4
class ListNode: def __init__(self, x): self.val = x self.next = None ''' Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter...
f7b2a08d245e7eb6b8559cd1297655ffcec77cf6
pzqkent/LeetCode
/14.py
1,017
3.8125
4
class Solution: def longestCommonPrefix(self, strs): if strs == []: return '' # find the shortest word in strs: # len1 = len(strs[0]) # for i in range(len(strs)): # len1 = min(len1, len(strs[i])) result = '' for i in ...
6ca0511e7f0075fd13a1a6f5e1fecf0a79e41637
eugenechantk/Introduction-to-Algorithms-Practices
/sorting_algo/mergesort.py
1,483
3.890625
4
def merge(arr,start,mid,end): nl = mid - start + 1 nr = end - mid left = [] right = [] for l in range(nl): left.append(arr[start+l]) for r in range(nr): right.append(arr[mid+1+r]) # add sentinel element so that, if one subarray runs out of elements to compare, there is still...
551baad84926aa306a847949b09d128ce577fe67
Jingtian1989/py
/directory/directory.py
675
3.546875
4
## distinctdict ## make sure no two different key has the same value class DistinctError(Exception): pass class distinctdict(dict): def __setitem__(self, key, value): try: value_index = list(self.values()).index(value) existing_key = list(self.keys())[value_index] ...
88b4def4533c0d6d06217b9791410aed4c8eb062
lauriiShii/PHYTON
/Ciclo/Alumno.py
1,856
3.796875
4
alumnos = {} alumnos["Carlos"] = ["Matematicas", "Lenguaje"] alumnos["Carmen"] = ["Matematicas"] alumnos["Julio"] = ["Conocimiento del medio", "Educacion Fisica"] alumnos["Samuel"] = ["Quimica","Fisica","Matematicas", "Conocimiento del medio"] alumnos["Tamzota"] = ["Quimica"] def menu(): print (""" Menu ...
b22a77a124273e75404bf80e48ec328b92699c58
djdays/class-xi-python-assignments
/assignment_23-10-2020.py
579
4.1875
4
# To find simple interest # with given Principle (p), No. of Years (n) and Rate of Interest (r) <<<<<<< HEAD p = float(input("Enter principle: ")) n = float(input("Enter number of years: ")) r = float(input("Enter the rate of interest: ")) ======= p = int(input("Enter principle: ")) n = int(input("Enter number of year...
32554c5f7a5253cce31a50506cf7899f0e50fccd
adrioter94/ISI-Project
/Fichas.py
3,215
3.609375
4
#Clase que representa una ficha class Fichas: #Una ficha se descomcompone en 5 partes: centro, arriba, abajo, derecha e izquierda. #Ademas, cada ficha tine zonas: pradera (P), aldea (A), camino (C), iglesia (I), y #bifurcacion (B). La zona se representa como un array de 15 numeros, cada numero relacionado #con un...
3139f25d8efa5179bc2ba8be7e7bb17557f2c168
marcoswebermw/learning-python
/sistema-operacional/arquivos/arq-4.py
289
3.625
4
# Abrindo um arquivo com 'open' sem passar o modo de acesso. # Lendo o arquivo inteiro de uma vez com 'read()'. # Depois usa o 'split(\n)' para dividir a string em uma lista. with open('arquivo.txt') as arquivo: linhas = arquivo.read().split('\n') for l in linhas: print(l)
58a634e983e99cb4fb6b5945d3e883ecd4a84b95
liujiang9/python0421
/dmeo/day10/code/选课系统/学生选课系统.py
7,453
3.640625
4
#学生:选课,修改密码操作需要输入验证码 #管理员:增加,删除选课输入验证码 course_lst = ["Python","java","web","unity","UI"] #保存用户 user_dic = {"zhang":{"name":"zhang","pwd":"123","course":[]}} Administrator = {"name":"admin","pwd":"admin"} import random #验证码 def verify_code(func): def inner(name): code = str(random.randint(1000,9999)) ...
747afa71037d806597934f608745e0ac90bbdb8b
shazam2064/python-for-noobs
/part3/while.py
126
3.90625
4
num = int(input("Enter num: ")) sum = 0 while num != 0: rem = num % 10 sum = sum + rem num = num // 10 print(sum)
1804e61d7762eec563ef3270caab2cb538b5d932
safeer-maker/Python-Practice
/Praticepython.org/String Lists Task 6.py
279
3.84375
4
inp = str(input("Enter the line ")) for i in range(len(inp)): if inp[i] == inp[len(inp) -1 -i]: continue else: print("This is not palindrome ") break print("string is palindrome") # this string is not appering in the code
70b5b31f341be29119ffc560a51c9b11bbe63021
EAGLE50/LearnLeetCode
/2020-07/Q415-add-strings.py
1,381
3.640625
4
# -*- coding:utf-8 -*- # @Time : 2020/8/1 10:57 # @Author : bendan50 # @File : Q415-add-strings.py # @Function : 字符串相加 # 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。 # 注意: # num1 和num2 的长度都小于 5100. # num1 和num2 都只包含数字 0-9. # num1 和num2 都不包含任何前导零。 # 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。 # @Software: PyCharm class Soluti...
302f9ca52bb83731dead811589207d006da1c285
Vikktour/Data-Structures-Algorithms-Implementations
/Dynamic Programming (DP)/LC329. Longest Increasing Path in a Matrix (Hard) - DFS.py
3,154
3.890625
4
""" Victor Zheng 04-10-2021 329. Longest Increasing Path in a Matrix (Hard) """ from typing import List """ Approach 1.1: TLE O(M*N*3^(M*N-1)) runtime O(M*N) space - where M=#rows, N=#cols DFS """ class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: M = len(matrix) N =...
c828f1ef79532b6b3759bc9904a4ace21163ccbb
evamal93/repo-py
/lesson1/task2.py
262
3.921875
4
total_seconds = int(input("Пожалуйста, введите время в секундах")) hours = total_seconds // 3600 minutes = total_seconds % 3600 // 60 seconds = total_seconds % 3600 % 60 print(f"hh {hours:02d} mm {minutes:02d} ss {seconds:02d}")
70f67f8d4e94f18d6238790d497b8ac5418f28b2
wangyunge/algorithmpractice
/eet/Longest_Substring_Without_Repeating_Characters.py
1,094
4
4
""" Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwk...
1e2fcc7f5d024d3d857767eb87d17a3417dff192
HBinhCT/Q-project
/hackerrank/Algorithms/The Power Sum/solution.py
468
3.640625
4
#!/bin/python3 import os # Complete the powerSum function below. def powerSum(X, N): dp = [1] + [0] * X for i in range(1, int(pow(X, 1 / N)) + 1): k = i ** N for j in range(X, k - 1, -1): dp[j] += dp[j - k] return dp[-1] if __name__ == '__main__': fptr = open(os.environ[...
5e6ca6281eb2c52917247cc96aa6ff7a9ca74480
marie-elia/Python-Course
/assignment1/1-d.py
630
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 12 03:34:24 2019 @author: marie """ #the user inputs a string composed of certain charcters string=input("Enter a string composed of lowercase a ,b,c ") countera= string.count('a')#counter for letter a counterb=string.count('b') #counter for letter b counterc=st...
a9795265c980d1313b3612171714f2a8e2ac940f
pwlodarczyk92/python-problems
/tasks/square_sum.py
346
4.1875
4
# write program reading an integer from standard input - a # printing sum of squares of natural numbers smaller than a # for example, for a=4, result = 1*1 + 2*2 + 3*3 = 14 a = int(input("pass a - ")) element = 1 result = 0 while element < a: result = result + element * element element = element + 1 print("...
289958e51c30d0afadd4a128101a4738baf43dd3
macostea/info-labs
/An 1/Sem 1/FP/Lab 11/compareFunctions.py
278
3.59375
4
''' Created on Dec 16, 2012 @author: mihai ''' def compareInts(x, y): if x<y: return -1 elif x==y: return 0 else: return 1 def compareNames(x, y): if x<y: return -1 elif x==y: return 0 else: return 1
8f0de04bc08ab546c50bcad5c890368d94468f58
p1x31/ctci-python
/leetcode/find_all_numbers_disappeared_in_an_array_448.py
1,118
3.625
4
from collections import Counter def findDisappearedNumbers(nums): #nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. # counter = Counter(nums) # print(counter) # return [i for i in range(1, len(nums) + 1) if i not in count...
c72466d2e6da555ef15355a1afebb5b75a9daa92
Morgenrode/MIT_OCW
/ex1.py
332
4.46875
4
'''Given three integers: print the largest odd integer''' x = int(input('First number: ')) y = int(input('Second number: ')) z = int(input('Third number: ')) # Evens are excluded, as even % 2 == 0 if max(x % 2 * x, y % 2 * y, z % 2 * z) != 0: print(max(x % 2 * x, y % 2 * y, z % 2 * z)) else: print('No odd numbers we...
71403fbc609f44495fa7a5ee8161cf635049db9e
hsjhita1/QAWork
/Python/PortalCommunity/Code/Files.py
892
3.84375
4
file = open("example_txt.txt", "r") ## r - read only, w - write only, r+ - read and write, a - append print(file.readline()) ## Reads the current line and moves on, .read reads current line to end of file file.readline() print(file.readline()) file.seek(0) ## Start at the beginning of a file and go to character 0 prin...
a13e018b8c10d3276c2c46e4722ebcfba331371a
elfeasto/house-price-models
/ML_Models/Parametric models/Multiple Linear/quadratic_sqft.py
771
3.78125
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression import tools from project_tools import * #load train data train_data, test_data = get_train_test_data() # add sqft_living ** 2 train_data["sqft_living_squared"] = train_data["sqft_living"] ** 2 #...
e9807fcfd9070862823b8221bba83ab14b2a60ae
ppinko/python_exercises
/string/hard_pig_latin_3.0.py
910
3.90625
4
""" https://edabit.com/challenge/pa7tTr3g4XaNkHoWC Write a function to convert a sentence to pig latin. Rules for converting to pig latin: For words that begin with a vowel (a, e, i, o, u), add "way" Otherwise, move all letters before the first vowel to the end and add "ay" For simplicity, no punctuation will be pres...
2403815f758c6f4148d9e57d7dd23ce2d507451d
gabrieleliasdev/python-cev
/ex055.py
1,185
4.21875
4
""" 055 - Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos. """ """ w1 = float(input(f"Type the weight of 1ª person: Kg ")) w2 = float(input(f"Type the weight of 2ª person: Kg ")) w3 = float(input(f"Type the weight of 3ª person: Kg ")) w4 = float(input(f"Type...
1d446841b603de049e685ea3a24f0279778e332d
Linkaan/Procjam2016
/src/level/bsp/rectangle.py
709
3.765625
4
class Rect(object): def __init__(self, x, y, w, h): self.x1 = x self.x2 = x + w self.y1 = y self.y2 = y + h self.w = w self.h = h self.center = (int((self.x1 + self.x2) / 2), int((self.y1 + self.y2) / 2)) def contains(self, x, y): if (self.w | se...
f8e6059bd05d9cb5c33751cba2238b812622eb1c
bondlee/leetcode
/114.py
1,058
3.8125
4
# coding: utf-8 # Created by bondlee on 2016/5/15 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from tree import get_tree from tree import TreeNode class Solution(object): def flatten(self,...
3e1931b5ff86fb08840895aa5f3851ac686a8cc5
MysteriousSonOfGod/Python-2
/Lyceum/lyc2/reverse.py
163
3.703125
4
# Тестируемая функция def reverse(s): if type(s) != str: raise TypeError('Expected str, got {}'.format(type(s))) return s[::-1]
156a860b0d9673c65b34b75c2344dd4dc79afd82
DitlevR/dat4sem2020spring-python-2
/Handins/Ex2/running-cli/printOrWrite.py
991
3.5625
4
import sys import csv import getopt def doFile(arguments): try: opts, args = getopt.getopt(arguments, "f", ["file"]) except getopt.GetoptError as err: # print help information and exit: print(err) # will print something like "option -a not recognized" usage() sys.exit(...
817d53b8074d14b99512ba20cb2293e4f5287f59
xudaniel11/interview_preparation
/is_sentence.py
1,028
3.984375
4
""" verify that a sentence is made up of words. e.g. "isawe" -> i, is, a, saw, awe, we """ def is_sentence(inpt): for i in range(len(inpt)): if helper(inpt, i, i) == True: return True return False def helper(inpt, head, tail): if tail == len(inpt) - 1: return True if is_wor...