blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
cfc98dd52b43295d212fdf4646b391d67e660d90
jerryhanhuan/LearnPython
/basic/do_dict.py
957
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # dict is map key => value { k1:v1,k2:v2} # define a dict with {} # define an empty dict d1 = {} # key 不会重复,key 唯一性 # 无序 # 查找和插入的速度极快,不会随着key的增加而变慢 # 需要占用较多内存,dict 是用空间来换取时间的一种方法 # key 必须是不可变对象,string,int 是不可变的,list 是可变的 d2 = {'jack':100,'lilei':100,'hanmm':100,'b...
3403092e68cfa4cd83b0de58d49d0b9de34dc36e
jerryhanhuan/LearnPython
/basic/do_iter.py
2,326
3.84375
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- #File Name:do_iter.py #Created Time:2019-07-16 05:48:33 #可直接作用于 for 循环的数据类型有以下几种: # #一类是 集合数据类型,如 list、tuple、dict、set、str 等 #一类是 generator,包括 生成器 和 带 yield 的 generator funciton #这样可直接用于 for 循环的对象统称为 可迭代对象 Iterable #可使用 isinstance() 判断一个对象是否是 Iterable 对象 from collections...
350106a829236590742a9295adc84608d015ab32
jerryhanhuan/LearnPython
/re/do_re_split.py
579
3.859375
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- #File Name:do_re_split.py #Created Time:2019-07-20 08:56:15 import re def str_split(): # split 无法识别连续的空格 str = 'a b c'.split(' ') print(str) #['a', 'b', '', 'c'] def re_str_split(): str = 'a b c' L = re.split(r'\s+',str) print(L) # ['a','b','c...
1a5541ac2b3af545ec206ad68986eaf8d6232512
dheerajps/pythonPractice
/algorithms/unsortedArrayHighestProduct.py
1,344
4.21875
4
# same as highestProduct.py # but find the maximum product possible by three numbers in an array without sorting it #so O(N) must be time requirements def getMaxProductOfThreeNumbers(array): import sys #Max product can be 3 maximum numbers or 2 minimum numbers and 1 max firstMax = -sys.maxsize-1 secondMa...
2d6928b4db17fb70ca3f9a188565755d2f5ebccb
dheerajps/pythonPractice
/zooKeeper/Zoo.py
528
3.828125
4
import animal class Zoo: def __init__(self): self.__animals =[] def add_animal(self,ani): self.__animals.append(ani) def show_animals(self): size = len(self.__animals) if size == 0: print('There are no animals in your zoo!') else: print('An...
7940ec94c488866b12288b662e51c6320cd507d3
Code-Girls/2015Summer_Chicken
/resources/mygame1.py
704
3.6875
4
# 1 import library import pygame from pygame.locals import * # 2 initialize the game pygame.init() width, height = 640,480 screen = pygame.display.set_mode((width.height)) # 3 load images player = pygame.image.load("resources/images/dude.png") # 4 keep looping through while 1: # 5 clear the screeen before drawi...
b577c7b5ab7731ade3cc1d79593918531609e884
xInflictz/Miscellaneous-Python-Scripts
/rngGame.py
5,870
3.875
4
import random import time global char_hp global enemy_hp global wins global loses char_hp = 100 enemy_hp = 100 wins = 0 loses = 0 def clear(): print("\n" * 250) def s_menu(): global char_hp, enemy_hp, wins, loses char_hp = 100 enemy_hp = 100 print("1)Start\n2)W/L Ratio\n3)Info\n4)Exit"...
5733d37a12e829c6d237d62d9f6a6d342c1a8043
suruirui/pyplay
/base/SweetPotato.py
1,304
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-09-22 11:35:10 # @Author : foxz (wc332431830@163.com) # @Link : suruirui.github.io # @Version : $Id$ #定义地瓜类 class SweetPotato: """docstring for SweetPotato""" #定义初始化方法 def __init__(self): self.cookedLevel = 0 self.cookedString = '生的' self.co...
6ca3ab4950f97e8494c5ddbd697f98386a77c969
suruirui/pyplay
/test/老王开枪栗子/2.py
871
3.78125
4
# -*- coding:utf-8 -*- #实现类、创建对象 #人 class Person(object): def __init__(self,name): super(Person,self).__init__() self.name = name #枪 class Gun(object): def __init__(self,name): super(Gun,self).__init__() self.name = name #枪名 #弹夹 class Clip(object): def __init__(self,maxN...
885a838c379f9035c436c0a1f09d67c9c21a6630
suruirui/pyplay
/test/func3.py
777
3.90625
4
# -*- coding:utf-8 -*- #局部变量和全局变量的区别1 #定义一个全局变量 温度 temperature = 0 def getTemperature(): #如果温度这个变量已经在全局变量的位置定义了,此时还想在函数中对这个全局变量进行修改的话 #那么 仅仅是 temperature=一个值 这还不够,,,此时temperature这个变量是一个局部变量,仅仅是和全局变量的名字 #相同罢了 #temperature = 33 #使用global用来对一个全局变量的声明 ,那么这个函数中的temperature = 33就不是定义一个局部变量,而是 #对...
a13acbfcad009e4e6cb392b9fa81a824989d1c7e
suruirui/pyplay
/test/demo7.py
1,487
3.78125
4
# -*- coding:utf-8 -*- #在房屋中存放家具 class House: def __init__(self,area,info,addr): self.area = area #总面积 self.info = info #户型 self.addr = addr #地址 self.leftArea = area #可用面积(初始为总面积) self.containItems = [] #容纳的家具 def __str__(self): msg = "房子的总面积是:%d,可用面积是:%...
d15b409aba0e82c2d755601dc3e880558c6d20e0
suruirui/pyplay
/base/back.py
398
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-01-12 # @Author : ${author} (${email}) # @Link : ${link} # @Version : $Id$ #定义类 class Car(object): def __init__(self): super(Car,self).__init__() self.wheelNum = 4 self.color = '蓝色' def start(self): print("start") c = Car(); print('车的轮子个数...
e3b10469f59fb79fdf6c208c4ac0f8d0b065ee8d
akshatasawhney/Binary-Search-2
/Problem1.py
1,938
3.71875
4
""" // Time Complexity : o(log n), where n is the number of elements // Space Complexity : o(1) // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : no """ class Solution(object): def leftBinSearch(self, nums, target): #for finding the first index l = 0 ...
54c73bf9f753a962a3a6b0bf744f9ec69965d04a
acgis-macl0468/gis4107-day08
/phoneUtils.py
1,071
3.890625
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Jake MacLean # # Created: 28-11-2017 # Copyright: (c) Jake MacLean 2017 # Licence: <your licence> #-------------------------------------------------------------------------------...
be7b0feee96e95b63f6c5452702c03685339bfd5
dphares/Gorehaven
/Gorehaven/colosseum.py
386
3.765625
4
def colosseum(): fight = input('Do you seek battle? (Y/N) ') while fight.lower() != 'y' and fight.lower() != 'n': fight = input('Do you seek battle? Input (Y)es or (N)o ') if fight.lower() == 'n': print('Live to fight another day.') import hub hub.hub() if fight...
06bb2b3d27e5d8d3875e22385cd9c4837c488def
MartyVos/Les5
/pe5_1.py
222
3.75
4
def convert(c): f = c * 1.8 + 32 return f def table(): print(' {} {}'.format("F", "C")) for c in range(-30, 50, 10): f = convert(c) print('{:5} {:6}'.format(f, float(c))) table()
32e8588930e8821ae35ef762dc37c3fa5368fd97
lyndsiWilliams/cs-module-project-algorithms
/sliding_window_max/sliding_window_max.py
1,063
4.5
4
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' def sliding_window_max(nums, k): # Your code here # Check if numbers array exists if nums: # Set an empty list for the max numbers to live max_numbers = [] ...
fb6da813a5cb08045fa33d876fb18c7521e2efc3
gmortuza/ctci-python
/2_linked_list/LinkedList.py
3,532
4.03125
4
import random class LinkedListNode: """ A single node of a linked list """ def __init__(self, val, next_node=None, prev_node=None): """ :param val: Value of the node :param next_node: :param prev_node: """ self.val = val self.next = next_node ...
ba87c6ee6a59b352d8e6e51d5eec9f90a9eabe51
Stahhl/codewars_python
/kata/A Needle in the Haystack.py
978
3.828125
4
# https://www.codewars.com/kata/56676e8fabd2d1ff3000000c/train/python import unittest def find_needle(haystack): for i, w in enumerate(haystack): if str(w).lower() == "needle": return f"found the needle at position {i}" # best # def find_needle(haystack): return 'found the needle at position %...
683d4921f21a261bd7ffb21dc2dbb302433fbe57
killreal13/python_patterns
/creational/abstract_factory/abstract_factory_example.py
1,936
4.03125
4
from abc import ABC, abstractmethod class AbstractTable(ABC): @abstractmethod def about_table(self): pass class WoodenTable(AbstractTable): def about_table(self): return 'деревянный стол' class PlasticTable(AbstractTable): def about_table(self): return 'пластиковый стол' ...
a7250f13d4b2894fc1d9d9f915205c19e1c6013f
killreal13/python_patterns
/behavioral/command_example.py
2,494
3.671875
4
from abc import ABCMeta, abstractmethod class Troop: """ Receiver - объект военного отряда """ def move(self, direction: str) -> None: print(f'Отряд начал движение {direction}') def stop(self) -> None: print('Отряд остановился') class Command(metaclass=ABCMeta): """ Баз...
ce7891d40d6011d6a09cdda49ce0507bb74edb1b
killreal13/python_patterns
/creational/builder/builder_concept.py
5,939
3.96875
4
""" Паттерн Строитель актуален только тогда, когда ваши продукты достаточно сложны, состоят из многих частей и требуют обширной конфигурации. Основное отличие паттерна Builder от других порождающих паттернов - то, что различные конкретные строители могут создавать несвязные друг с другом продукты. По простому - различ...
da24323466278277536c28452087bfd90fe7c76e
killreal13/python_patterns
/creational/prototype/prototype_example.py
864
3.609375
4
import copy class Prototype: def __init__(self): self._objects = {} def register_object(self, name, obj): self._objects[name] = obj def unregister_object(self, name): del self._objects[name] def clone(self, name, **attr): obj = copy.deepcopy(self._objects.get(name)) ...
87731860b85423357493b39dc6badaef5e663123
guesschess/Interactive-programming
/Memory.py
2,144
3.578125
4
# implementation of card game - Memory import simplegui import random turns = 0 # Check the game's state list1 = [] list2 = [] # the number of revealed cards state = 0 # helper function to initialize globals def new_game(): global turns,started,list1,list2,state,exposed turns = 0 state = 0 list1 = [...
01a7c6c837797069f06a4da06e5bb4a846e0b583
charlottemoonen/P3_BRA_04
/Snakebis.py
3,000
3.609375
4
import numpy as np from sense_hat import SenseHat import time import random #if the snake encounter the reward def appleOnMe(board, tail, x,y): if board[x][y] == A: appleIsOnBoard = False while not appleIsOnBoard: x_gen = random.randint(0,7) y_gen = random.randint(0,7) ...
c3aa03a45973f31bf0ae784cd99773cff2ec60ee
show2214/atcoder
/atCoderBeginnerContest162_b.py
208
3.84375
4
if __name__ == "__main__": N = int(input()) i = [] for num in range(1, N+1): if num % 3 == 0 or num % 5 == 0: continue else: i.append(num) print(sum(i))
65002cb92fb39b79c3bf46a956ea81f638e652e2
jml312/Automation
/ConfirmLogin.py
771
3.796875
4
def confirmLogin(system): global username, password username = input("Enter your {} Username: ".format(system)) password = input("Enter your {} Password: ".format(system)) entered_correctly = input("Was your information entered correctly (type 'no' if not or hit enter to continue)? ") print("\n") ...
c96af2db798f2775ad1eecb45e4d67e2b9574feb
mariettas/SmartNinja_Project_python1_homework
/mood_checker.py
389
4.0625
4
mood= input ("What mood are you in?") if mood == "happy": print("It is great to see you happy!") elif mood == "nervous": print("Take a deep breath 3 times.") elif mood == "sad": print("Cheer up!") elif mood == "excited": print("Glad to see you are excited!") elif mood == "relaxed": print ("How come...
a2b4f9b45b1888a518e7db8a687c3bf452aca122
manu4xever/leet-code-solved
/reverse_single_linked_list.py
506
4.1875
4
Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): ...
3916c42efe8d877ab1d041c32dda110b2c81a1b1
manu4xever/leet-code-solved
/move_zeroes.py
747
4.09375
4
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do no...
a2db47054e18ed8d18ebc3643e34bb18d210becf
AldoRastrelli/Random-Tweet-Generator
/generar.py
1,251
3.734375
4
import contadores FAVORITOS = 'tweets_favoritos.txt' def generar(cuentas): """Genera un tweet aleatorio considerando las cuentas ingresadas por parámetro, lo imprime y pregunta si desea guardarlo o no. Si es asi, lo guarda en {FAVORITOS}.""" if not cuentas: print('Ninguna de las cuentas ingresada...
0d4b6e26e09ea7d90e4d45941f07a4d9046ba1b4
Hety06/caesar_cipher
/caesar_cipher.py
878
4.1875
4
def shift(letter, shift_amount): unicode_value = ord(letter) + shift_amount if unicode_value > 126: new_letter = chr(unicode_value - 95) else: new_letter = chr(unicode_value) return new_letter def encrypt(message, shift_amount): result = "" for letter in message:...
1eb92fd964d785db16d04628b9734810a5460374
anterra/area-calculator
/area_calculator.py
1,016
4.15625
4
import math class Rectangle: def __init__(self, length1, length2): self.length1 = length1 self.length2 = length2 def area(self): area = self.length1 * self.length2 return area class Circle: def __init__(self, radius): self.radius = radius def area(self): ...
f8cb2d4ff4976169893c680ba37018de7e936e34
dileep208/dileepltecommerce
/test/one.py
341
4.25
4
# This is for printing print('This is a test') # This is for finding the length of a string s = 'Amazing' print(len(s)) # This for finding the length of hippopotomus s='hippopotomous' print(len(s)) # This is for finding the length of string print('Practice makes man perfect') # finding the length of your name s = 'dil...
f27115420c276269737c3594cc9e1e87a3a555fa
siva6160/helloworld
/calculator.py
1,169
3.984375
4
import math def sum(a,b): a+=b return a def sub(a,b): a-=b return a def div(a,b): q=a/b r=a%b print(q,r) def mul(a,b): a*=b return a def sr(a): s=math.sqrt(a) return s while(True): print("eneter your choice") print("\n 1.ADDITION","\n 2.SUBSTRACTION...
46f4ccac098130227ddf177fc99365cbffa31f86
siva6160/helloworld
/becomde9-3.py
236
4.15625
4
import math as m def pow(num,p): res=num**p return res num=int(input("enter a number")) p=int(input("enter a num")) s=pow(num,p) print(s) print(m.pow(num,p)) print(m.sqrt(num)) print(m.ceil(num)) print(m.floor(num))
4ab1d0e187e34c520e411b5fdff597419f852438
siva6160/helloworld
/swap.py
98
3.859375
4
a=int(input("enter a number")) b=int(input("enetr a number")) print(a,b) a,b=b,a print(a,b)
a2a68fb2cace37ca150c497913eba71e1a61931b
siva6160/helloworld
/becomder6-2.py
137
3.890625
4
def sum(n): #n=int(input("enter")) i=0 sum=0 while i<n: i+=1 sum=sum+i print(sum) sum(n=10)
f3e2c720fc5fb7045a5eb8727656c23e4cc56199
siva6160/helloworld
/becomde9-1.py
74
3.796875
4
def pow(num,p=2): res=num*(P*P) return res s=pow(3) print(s)
d5ab73fa4547cb004174e31d2b762251e976d908
siva6160/helloworld
/becomde8-1.py
125
3.953125
4
def sum(a=0,b=0): res=a+b return res a=int(input("enter a num")) b=int(input("enter a num")) s=sum() print(s)
86f339f0aa9f239a2e2711b458f2e57e6cbc96c9
siva6160/helloworld
/becomde8-3.py
128
3.921875
4
def sum(a,b): res=a+b return res a=int(input("enter a num")) b=int(input("enter a num")) s=sum(a=0,b=0) print(s)
580e061bc9d72a90ed2411c6ea7b8393f3b6e0f4
johnnyferreiradev/python-course-microsoft
/formatting-strings.py
295
4.1875
4
first_name = 'Johnny' last_name = 'Ferreira' output = 'Hello, ' + first_name + ' ' + last_name output = 'Hello, {} {}'.format(first_name, last_name) output = 'Hello, {1} {0}'.format(first_name, last_name) # Only available in Python 3 output = f'Hello, {first_name} {last_name}' print(output)
e130b3d95ec21002a0b03f72524ac09d98e36e07
Wiatrowiec/Robotyka_Astar
/astar.py
3,138
3.5625
4
from math import sqrt class Node(): def __init__(self, parent=None, position=None): self.parent = parent self.position = position self.g = self.h = self.f = 0 def __eq__(self, other): return self.position == other.position def path(current_node,marx): pathx=[] curre...
75f71183b5de65515fd1b2e885a345d5aa947e48
vinaykumar7686/Algorithms
/Data Structures/Hashmap/Isomorphic Strings.py
1,582
4.0625
4
$ Isomorphic Strings ''' Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same char...
8613d03783d697151dd14f9ac56c6ec0db3a1d74
vinaykumar7686/Algorithms
/Algorithms/Sorting/Selection_Sort.py
680
3.984375
4
# Time Complexity = O(N^2) nums = list(map(int, (input("Enter all the numbers to be sorted (seperate with spaces ) : ")).split(" "))) n = len(nums) def selection_sort(nums, n): i=0 while i<n-1: # Initialising minimum index (index that is to be worked upon) mi = i j = i+1 while ...
a7a5cbedf25dc380bfcf6c152cfa4848d32f0c55
vinaykumar7686/Algorithms
/Data Structures/Binary-Tree/Binary Search Tree/[BST] Validate Binary Search Tree.py
2,161
4.375
4
# Validate Binary Search Tree ''' Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node...
867ffc604bc02ee32ef1798070530ef9861ef0a1
vinaykumar7686/Algorithms
/Algorithms/Dynamic_Programming/Nth_Fibonacci_No/fibonacci _basic _sol.py
1,022
4.40625
4
def fibo_i(n): ''' Accepts integer type value as argument and returns respective number in fibonacci series. Uses traditional iterative technique Arguments: n is an integer type number whose respective fibonacci nyumber is to be found. Returns: nth number in fiboacci series ''' # Sim...
a18a38d23b15ccc47d87ad0f440773e9721ddbe8
vinaykumar7686/Algorithms
/Algorithms/Intresting_Solution/max_product.py
211
3.671875
4
def maxProduct(nums): a, b = float('-inf'), float('-inf') for x in nums: if x>a: a, b = x, a elif x>b: b = x return (a-1)*(b-1) print(maxProduct([1,2,3,4,5]))
4ad052ae36aeba663eb8e35cda617fc7c9321e0b
gregr/uriel
/uriel/core/tuplemath.py
1,228
3.9375
4
# Gregory Rosenblatt # 12/8/05 # some basic operations that treat tuples as vectors def Add2d(t, t0): # vector addition of t and t0 i,j, = t x,y = t0 return (i+x, j+y) def Add3d(t, t0): i,j,k = t x,y,z = t0 return (i+x, j+y, k+z) def Subtract2d(t, t0): # diff between vector t and its reference ...
f04e1c9e1d991242d1dcce33de00c651125572a7
ziolkowskid06/Python_Crash_Course
/ch10 - Files and Exceptions/10-03. Guest.py
222
4.4375
4
""" Write a program that prompts the user for their name. """ name = input("What's your name? ") filename = 'guest.txt' # Save the variable into the .txt file with open(filename, 'w') as f: f.write(name)
daddc2badb17111c59d9406fdeb09dd7871b620e
ziolkowskid06/Python_Crash_Course
/ch05 - IF Statements/5-02. More Conditional Tests.py
673
4.125
4
""" Write more conditional tests. """ # Equality and iequality with strings. motorcycle = 'Ducati' print("Is motorcycle != 'Ducati'? I predict False.") print(motorcycle == 'ducati') print("\nIs motorycle == 'Ducati'? I predict True.") print(motorcycle == 'Ducati') # Test using lower() method. pc = 'DELL' p...
4821ae626a466adf86513a9e5c2ff35f259b9b89
ziolkowskid06/Python_Crash_Course
/ch09 - Classes/9-01. Restaurant.py
867
4.0625
4
""" Make a class called Restaurant. """ class Restaurant: """Model of restaurant""" def __init__(self, restaurant_name, cuisine_type): """Initialize restaurant_name and cuisine_type""" self.restaurant_name = restaurant_name.title() self.cuisine_type = cuisine_type de...
58ca8613f51031792f48d896a3f5c3d6a4cfc565
ziolkowskid06/Python_Crash_Course
/ch05 - IF Statements/5-08. Hello Admin.py
473
4.4375
4
""" Make a list of five or more usernames, including the name'admin'. Imagine you are writing code that will print a greeting to each user after they log in to a website and the question for admin. """ names = ['anna', 'elizabeth', 'julia', 'kim', 'admin', 'rachel'] for name in names: if name == 'admin': ...
f688caac55f4fc4226133ad231e6cbedf280e28a
ziolkowskid06/Python_Crash_Course
/ch05 - IF Statements/5-10. Checking Usernames.py
586
4
4
""" Create a program that simulates how websites ensure that everyone has a unique username. """ current_names = ['anNA', 'EmmA', 'eliZabeTh', 'koRtney', 'jorDan', 'EVA', 'patricia'] new_users = ['rachel', 'samantha', 'EMMA', 'clementine', 'kendra', 'evA'] copy_current_names = [name.title() for name in current_n...
d90c7e345eb4fe782187b003523f9caa1909447c
ziolkowskid06/Python_Crash_Course
/ch07 - User Input and WHILE Loops/7-10. Dream Vacation.py
494
4.15625
4
""" Write a program that polls users about their dream vacation. """ poll = {} while True: name = input("What's your name? ") vacation = input("If you could visit one place in the world, " "where would you go? ") poll[name] = vacation quit = input("Stop asking? (yes/no) "...
b9014e87d1d5167c8cdcd0f0837609b7d61e240e
ziolkowskid06/Python_Crash_Course
/ch03 - Introducing Lists/3-09. Dinner Guests.py
319
4.21875
4
""" Working with one of the programs from Exercises 3-4 through 3-7 (page 42), use len() to print a message indicating the number of people you are inviting to dinner. """ # Print a number of elements guest_list = ['mary jane', 'elizabeth hurtley', 'salma hayek'] print(f" There are {len(guest_list)} people invi...
a8d80f6fec470c019400c1e19e43e6e0deb0aaca
ziolkowskid06/Python_Crash_Course
/ch08 - Functions/8-05. Cities.py
275
4.09375
4
""" Write a function called describe_city() that accepts the name of a city and its country. """ def describe_city(city, country='Poland'): """Print the city and its country.""" print(f"{city.title()} is in {country.title()}.") describe_city('Gdynia')
30176a4c40a0682963e4d0d9de8d27004b191ff1
ziolkowskid06/Python_Crash_Course
/ch07 - User Input and WHILE Loops/7-02. Restaurant Seating.py
277
4.21875
4
""" Write a program that asks the user how many people are in their dinner group. """ seating = input('How many people are in your dinner group?\n') seating = int(seating) if seating > 8: print("You need to wait for a table.") else: print("Table is ready!")
ad5d1d06850d1034e9f8c7666f294b20798510f9
ziolkowskid06/Python_Crash_Course
/ch09 - Classes/9-13. Dice.py
787
4.0625
4
# Import randint function (random number in the range) from random import randint class Die: """ Create a die of a different number of sides. Roll this dice. """ def __init__(self, sides=6): """Initialize number of sides and rolls""" self.sides = sides self.ro...
d221e985cba39c40bac19bf1d17d9b1cb93e4fd5
ziolkowskid06/Python_Crash_Course
/ch16 - Downloading Data/16-02. Sitka-Death Valley Comparison.py
2,669
3.765625
4
""" Make a direct comparison between temperature rages in Sitka and Death Valley. You need identical scales on the y-axis. """ import csv from datetime import datetime from matplotlib import pyplot as plt def get_weather_data(filename, dates, highs, lows, date_index, high_index, lo...
100a258024446e97d4dcb301b05962a3e1c677f7
ziolkowskid06/Python_Crash_Course
/ch08 - Functions/8-12. Sandwiches.py
344
4.03125
4
""" Write a function that accepts a list of items a person wants on a sandwich. """ def make_sandwich(*toppings): """Show a lits of items a person wants on sandwich""" print("Summary of sandwich:") for topping in toppings: print(f"\t- {topping}") make_sandwich('ham', 'cheese', 'onion...
4baad7a495cb3bc9f781d1cb0c3f31019c1049d4
talbi28/GMM_tutorial
/GMM_examples.py
1,391
3.53125
4
import numpy as np from matplotlib import pyplot as plt from numpy.random import multivariate_normal as mvn from GMM import * import pickle """ Example Gaussian Mixture Model code to accompany EM tutorial. P.L.Green University of Liverpool (1) Engineering Data Analytics Ltd. (2) (1) p.l.green@liverpool.ac.uk (2) en...
e64f15fcf70aeae1684679f8e53c4d56d5b3ff39
Mudd-Fish/web-caesar
/caesar.py
1,106
3.9375
4
def encrypt(text, rot): return rotate_char(text, rot) def rotate_char(mess, rot): alphabet = 'abcdefghijklmnopqrstuvwxyz' up_alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' encrypted = '' for char in mess: if(char.isalpha()) == False: encrypted = encrypted + char elif(char == str...
af3608460d77fede0b7a6932527f6c24d1dc37f6
smallpondtom/Beginners_level_python_programs
/optimization_practice.py
746
3.90625
4
# This is a easy python code to just practice the use of Scipy optimization from scipy.optimize import minimize def objective(x): x1 = x[0] x2 = x[1] x3 = x[2] x4 = x[3] return x1*x4*(x1 + x2 + x3) + x3 def constraint1(x): return x[0]*x[1]*x[2]*x[3] - 25.0 def constraint2(x): sum_eq = 40 ...
323d66219db024789b31080a91c0f2b495dfe95a
kkin1995/simulations
/simple-pendulum/main.py
2,534
3.625
4
from simple_pendulum import SimplePendulum from phase_space import multiple_phase_plot, momentum from energy import plot_energy from all_in_one import plot_all import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import yaml # Importing the parameters with open('parameters.yaml'...
a9090c9ce6097f8c693b29719a8f72d68474d812
srnortw/Basic_Programs
/Fibonacci_Numbers.py
714
4.09375
4
fibonacci_number=[0,1] my_quantity=input('How many fibonacci numbers Do you need:') my_index_of_number=input('what index of fibonacci numbers Do you want:') my_quantity=int(my_quantity) my_index_of_number=int(my_index_of_number) for index in range(0,my_quantity-2): new_number=fibonacci_number[index]+fibonacci_n...
d1c3136fd73fc105b667041ac1a91af6141147c7
srnortw/Basic_Programs
/Prime_Numbers_Of_Random number.py
1,167
3.96875
4
def Prime_Numbers_Of_Random_Number(min,max): import random a = random.randint(min,max) old_a = a c = set() for x in range(a-1,1,-1): if a%x==0: b=a//x gate = True for p in range(x-1,1,-1): if x%p==0: a=x ...
9ac35198dc678adbeabc3ae794922aa176cd83a7
evolutek/libpathfinding
/python/interface.py
2,323
3.546875
4
from tkinter import * class Interface: def __init__(self): self.window = Tk() self.button = Button(self.window, text="Close", command=self.window.quit) self.button.pack() self.canvas = Canvas(self.window, width=1500, height=1000, background='black') self.mapimage = PhotoImage(file="map.png") self.canvas...
6c05133e2b76ac4fe3c7cc4dfc8d25961e99d5fe
farhadiman/assignment-1-farhadiman
/region_analysis/binary_image.py
1,908
3.703125
4
from __future__ import division import numpy as np import cv2 class binary_image: def compute_histogram(self, image): """Computes the histogram of the input image takes as input: image: a grey scale image returns a histogram""" hist = [0]*256 #hist = cv2.calcHist...
8cff20092081d06750fcde60f824d4de532bd41a
sanjayMamidipaka/cs1301
/.history/test_20210708160300.py
610
4
4
# -*- coding: utf-8 -*- def summerWeather(weather): output = ['sunny', 0, 'rainy', 0] sunnyDays = 0 rainyDays = 0 for char in weather: if char == 's': sunnyDays += 1 elif char == 'r': rainyDays += 1 output[1] = sunnyDays output[3] = rainyDays return ...
4b8e045bbf85f1c7ce22e33344df6482035a4411
sanjayMamidipaka/cs1301
/.history/test_20210708154613.py
136
3.75
4
# -*- coding: utf-8 -*- print(88/2) print(type(88/2)) print(int(8.8) + float("3")) print(True and False and True or False or not True)
ca5b6793ea578e1748cecbcefbce9b8b52289441
allo0001/gb_algorithms
/les1/task6.py
309
3.921875
4
""" Пользователь вводит номер буквы в алфавите. Определить, какая это буква. """ ALPHABET = 'abcdefghiklmnopqrstvxyz' num = int(input('введите номер буквы в алфавите :')) print(f'Это букава - {ALPHABET[num-1]}')
f6d41f51b486e01e034d86725b7cda9ee0f91ae7
SyedJawadShah/CS5590Python-Spring2018
/Lab 2 Assignemnt 2/Source/Lab 2 Question 2.py
5,542
4.46875
4
# The purpose of this exercise is to have a contact list on which a user can perform different operations, Edit, display,etc # The contact details are stored in a list of dictonaries, named Contact_list Contact_list = [{'name':'Anthony Reed','number':'0000000001','email':'a@gmail.com'}, {'name':'Thom...
364035afe64a840ac1425ad3bb650bc075d6f297
happyflying-web/algorithms_practice
/DS_python_version/sum-of-left-leaves.py
764
3.71875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' 当需要用到父节点的信息时,需要用栈的数据结构来保存父节点的信息 ''' class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: list_1=[] sum =0 if root : ...
990d6ff881bf52888c4f534884b5919c13d83ff5
sanchezg/coursera-algorithms
/algorithmic-toolbox/fractional_knapsack/fractional_knapsack.py
931
4.0625
4
# Uses python3 import sys def get_optimal_value(capacity, weights, values): """knapsack problem: get the optimal fractional configuration of values/weights that fills the capacity. """ assert len(weights) == len(values) value = 0. weights_values = list(zip(weights, values)) weights_va...
02f49428243fd088726c7af53371624922b2b0bf
sanchezg/coursera-algorithms
/algorithmic-toolbox/primitive_calculator/primitive_calculator.py
948
3.640625
4
# Uses python3 import sys def optimal_sequence(n): sequence = [] a = [0] * (n + 1) for i in range(1, n + 1): a[i] = a[i - 1] + 1 # At least add one to the last number if (i % 2 == 0): a[i] = min(1 + a[i // 2], a[i]) if (i % 3 == 0): a[i] = min(1 + a[i // 3]...
4e79798ade9d5784c244de85ead409e100f1c2e2
hjs6877/LottoMachine
/src/com/soom/main/MainAppCopy.py
998
3.625
4
""" 1. Lotto 번호 생성기 작업. 2016.02.19 (1) 초기 작업 목표 - 6자리의 랜덤 숫자를 생성한다. - 사용자로부터 게임 횟수 입력을 받아서 게임당 6자리의 랜덤 숫자를 생성한다. - 생성한 게임을 DB에 저장한다. - 생성한 게임을 프린트로 출력한다. - 생성한 게임을 메일로 발송한다. - 회차별 당첨 번호를 입력 및 저장한다. (2) 중간 목표 - 그동안 DB에 저장 된 생성 번호와 회차별 번호를 확률적 통계를 내어 번호를 생성한다. (3) Advanced 목표 - Machine Le...
707c8e2164d0b84d52615c3733f0363db2241dcd
mysqlplus163/aboutPython
/somethingUnuseful.py
503
3.96875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi" # Date: 2017/7/11 """ ??? """ # def whatyouneed(): # while True: # yield "Python" # # i = 1 # # for x in whatyouneed(): # print(x) # i += 1 # if i > 10: # break def how_many(the_list): return "There {0} {1[0]} {...
dc328059f0064b97e23eb8bf2e3bc3c538032042
mysqlplus163/aboutPython
/while_demo/while_demo.py
838
3.546875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi" # Date: 2017/3/13 # 使用while循环实现输出2 - 3 + 4 - 5 + 6 ... + 100 的和 # m = 0 # n = 2 # while n <= 100: # if n % 2 == 0: # 偶数 # m = m + n # else: # m = m - n # n += 1 # print(m) # # m2 = 0 # for i in range(2, 101): # if ...
81ac8f5168c46f9e66d6f15f6976106df04c325f
mysqlplus163/aboutPython
/operator_precedence/demo1.py
1,255
3.828125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi" # Date: 2017/6/9 """ 逻辑运算符的优先级 官方文档: https://docs.python.org/3.6/reference/expressions.html#operator-precedence 优先级由高到低: not >> and >> or 就是遇到这三个有not就先计算not,没有not了就计算and,最后再计算or """ # 根据上面的优先级顺序,先计算True and False => False or False => False pr...
119351ba21a6b1f5ff1a6e0750f6ef8d779ab64c
mysqlplus163/aboutPython
/map_demo/demo1.py
607
3.53125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi" # Date: 2017/6/16 s = 'ab;cd|efg|hi,jkl|mn\opq;rst,uvw/xyz' sign = ';|\/,' def my_split(s, sign): s1 = [s] for i in sign: t = [] print(list(map(lambda x: x.split(i), s1))) map(lambda x: s1.extend(x.split(i)), s1) ...
79e606f008f1b4bd24f040a8f23ff17744ba1392
mysqlplus163/aboutPython
/decorator_demo/demo13.py
689
3.5625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi" # Date: 2017/6/21 import time import random def auth(func): def wrapper(): name = input("用户名:").strip() password = input("密码:").strip() if name == "Andy" and password == "123": print("验证成功!") func...
236e6212d41f318a7e89188899f67cf635253cd1
mysqlplus163/aboutPython
/20170106.py
394
3.578125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi" # Email: master@liwenzhou.com # Date: 2017/1/6 import time l1 = [1, 2, 3] s1 = "Hello World!" def c(l): l.append(4) print(l) print(id(l)) def f(s): s += "hi" print(s) c(l1) print(l1) print(id(l1)) f(s1) print(s1) def fu...
d8bf5c776f3d205b611959efb6af840f3c55d1e6
mysqlplus163/aboutPython
/20170626/demo1.py
366
4.1875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Python中的迭代 list1 = [1, 2, 3, 4, 5] # index = 0 # while index < len(list1): # print(list1[index]) # index =index + 1 # for循环 for index in range(len(list1)): # rang(3) -> 0, 1, 2 print(list1[index]) # # 区别于简单的重复 # while True: # print("老男孩教育暑期实训")
895909874d0425fd75fdd94dde3dc0c1949ab121
mysqlplus163/aboutPython
/20170628/demo4.py
653
4.03125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # 倒计时的例子 def countdown(n): print("倒计时开始") while n > 0: yield n n = n - 1 print("发射") ret = countdown(5) # 得到生成器 # print(next(ret)) # 打印倒计时开始",暂停 返回n -->5 # print(next(ret)) # n = 4, 暂停 返回n -->4 # print(next(ret)) # n = 3, 暂停 返回n -->3 # p...
b73aff63a7aad9e2c98c4890643df5679e42441f
mysqlplus163/aboutPython
/for_demo.py
980
4
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi" # Date: 2017/1/3 i = 0 name = input("name:").strip() if name == "": print("...") elif name == "1": print("1") else: while True: for i in range(3): p = input("password:").strip() if i < 2: ...
26ca37948220273b5d4ee55ab40e22f1f8c3c527
elenaoat/PythonProjects
/gameoflife.py
2,315
3.65625
4
import pygame import random import sys width = 640 height = 400 screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() dots = set() #dot_num = random.randint(5, 50) #for x in range(dot_num): # x = random.randint(1, 10) # y = random.randint(1, 10) # dots.append((x*10, y*10)) dots.update...
76d86bc710e60ee97c68d3f7e3a50165fcf0515b
wyao/intro_to_ai
/hw2/neural_net_impl.py
10,525
4.21875
4
from neural_net import NeuralNetwork, NetworkFramework from neural_net import Node, Target, Input import random import math import py.test INPUT = 1 HIDDEN = 2 OUTPUT = 3 # <--- Problem 3, Question 1 ---> def FeedForward(network, input): """ Arguments: --------- network : a NeuralNetwork instance input :...
59da2eab9668722ad88292e90ace5707717bf956
hannahbrooks/csc190
/lab4/hash.py
150
3.671875
4
hash(x): if (10<x<100): x = x-7 return x else: while(x<=10): x=x+8 while (x>=100): x=x-9 return x
cdd741bf76579bd97882e733b6df651aa54f72cf
clintKunz/Whiteboard-Pairing
/LargestContiguousSum/model_solution.py
670
3.84375
4
# We'll use a greedy algorithm to check to see if we have a # new max sum as we iterate along the along. If at any time # our sum becomes negative, we reset the sum. def largestContiguousSum(arr): maxSum = 0 currentSum = 0 for i in range(len(arr)): currentSum += arr[i] if maxSum < curre...
ac647ee665b012f41d4d5259e5dca048691bae27
pszhilina/HW_6
/new_list.py
313
3.9375
4
# на основе цикла for l = [] for i in [2, 4, 9, 16, 25]: l.append(pow(i, 0.5)) print(l) # на основе функции map print(list(map(lambda a: pow(a, 0.5), [2, 4, 9, 16, 25]))) # в виде генератора списка L = [2, 4, 9, 16, 25] l = [pow(i, 0.5) for i in L] print(l)
296bf35b43aa11ff060200c30a02204f1e7f7cf0
SahibSingh1311/Session_3
/venv/hackerRank2.py
74
3.5625
4
x = int(input()) if x/4 or x/400: print("True") else: print(false)
e9621aefd9c4bebdf50bfe4d8753f786d57f6bb8
SahibSingh1311/Session_3
/venv/session3e.py
412
4.03125
4
#Bitwise operators a = 8 #1000 b = 12 #1100 c = a & b #1000 print(c) c= a|b #1100 print(c) c= a^b #0100 print(c) x = 12 y = 3 #right shift (cause divide with 2^3) #z = x >> y #1100 >>3 -> _ _ _ 1 #print(z) #left shift( cause mmuktiply 2^3) z= x<<y print(z) x=-13 #11011 y=2 z= x>>y print("z is ...
c168cf7736a2b5eac41a4dc95907334e197f9f50
SahibSingh1311/Session_3
/session4f.py
260
3.875
4
names = ["John", "Fionna", "Kia"] names[0] = "Johns Watson" print(names) # immutable names1 = ("John", "Fionna", "Kia") # names1[0] = "John Mutable" # names.append("Kim") print (names1) # convert tuple into list newNames = list(names1) print(newNames, type(newNames))
a71786ad24f13ec1523f78215e3a0ffed5a5c2c9
SahibSingh1311/Session_3
/session8c.py
269
3.734375
4
class Product: counter = 0 def __init__(self): Product.counter = Product.counter +1 def showObjects(self): print("Number of Objects:{} ".format(Product.counter)) p1 = Product() p2 = Product() p3 = Product() p4 = p1 p5 = p3 p5. showObjects()
fcbb643dc0bc56467c14cd47b8f5f4ead70e8e8c
jadiribnahasan/Python-Numpy-Pyplot-Pandas
/MonteCarloSimulationForPiValue.py
687
3.625
4
from matplotlib import pyplot as plt import numpy as np import math as math import random as rand def monteCarloPi(trials, radius): hits = 0 for i in range(trials): xr = rand.uniform(0, radius) yr = rand.uniform(0, radius) distance = math.sqrt(xr**2 + yr**2) if(distance <= radi...
13a4f8bb2a6dec0589a36a00ace4886727561e40
dickyardt/discrete-math
/assigment_01/Zm.py
1,104
4.09375
4
# Regner i Zm, for vilkårlige m # Calculate for Zm for arbitrary number for m print("How to use it: It takes three inputs.\nEnter an integer value for each and it will calculate it the result and shows on the screen ") a = int(input("Enter a value of A: \n")) b = int(input("Enter a value for B: \n")) m = int(input("Ent...
00e1765081dea2c16b6151935b2823a540302888
NataliPotter/DAT110_eksenpler_2021_New
/filer/fil_leser.py
1,223
3.5
4
#Filer # Tekstfiler # CSV - comma-separated values # Binærfiler #Modus # r - ønsker å lese fila (Read) # w - ønsker å skrive fila, ønsker å slette ei eventuell gammel fil (Write) # a - Ønsker å skrive fila, legger til på slutten hvis den finnes (Append) # x - Ønsker å skrive fila, feiler om fila aller...
82e64036228100681765e752dcd0fd96ddfda928
NataliPotter/DAT110_eksenpler_2021_New
/funksjoner/diamant.py
970
3.59375
4
# Diamant-eksemplet med funksjoner. Viser hvordan man med refaktorering kan # unngå å kopiere kode # # * # * * # * * # * * # * def tegn_forste_del_linje(lengde, hvilken_linje): for tall in range(lengde): if tall == lengde-1-hvilken_linje: print("*", end="") else: pr...
c41f4dcd82e4b041185764f8646f5de6dc5b1ab6
Alex-Angelico/math-series
/math_series/series.py
1,337
4.3125
4
def fibonacci(num): """ Arguments: num - user-selected sequence value from the Fibonacci sequence to be calculated by the funciton Returns: Calculated value from the sequence """ if num <= 0: print('Value too small.') elif num == 1: return 0 elif num == 2: return 1 else: return fi...